Date: (Wed) Apr 13, 2016

Introduction:

Data: Source: Training: https://d37djvu3ytnwxt.cloudfront.net/asset-v1:MITx+15.071x_3+1T2016+type@asset+block/WHO.csv New:
Time period:

Synopsis:

Based on analysis utilizing <> techniques, :

Summary of key steps & error improvement stats:

Prediction Accuracy Enhancement Options:

  • transform.data chunk:
    • derive features from multiple features
  • manage.missing.data chunk:
    • Not fill missing vars
    • Fill missing numerics with a different algorithm
    • Fill missing chars with data based on clusters

[](.png)

Potential next steps include:

  • Organization:
    • Categorize by chunk
    • Priority criteria:
      1. Ease of change
      2. Impacts report
      3. Cleans innards
      4. Bug report
  • all chunks:
    • at chunk-end rm(!glb_)
  • manage.missing.data chunk:
    • cleaner way to manage re-splitting of training vs. new entity
  • extract.features chunk:
    • Add n-grams for glbFeatsText
      • “RTextTools”, “tau”, “RWeka”, and “textcat” packages
  • fit.models chunk:
    • Classification: Plot AUC Curves for all models & highlight glbMdlSel
    • Prediction accuracy scatter graph:
    • Add tiles (raw vs. PCA)
    • Use shiny for drop-down of “important” features
    • Use plot.ly for interactive plots ?

    • Change .fit suffix of model metrics to .mdl if it’s data independent (e.g. AIC, Adj.R.Squared - is it truly data independent ?, etc.)
    • create a custom model for rpart that has minbucket as a tuning parameter
    • varImp for randomForest crashes in caret version:6.0.41 -> submit bug report

  • Probability handling for multinomials vs. desired binomial outcome
  • ROCR currently supports only evaluation of binary classification tasks (version 1.0.7)
  • extensions toward multiclass classification are scheduled for the next release

  • fit.all.training chunk:
    • myplot_prediction_classification: displays ‘x’ instead of ‘+’ when there are no prediction errors
  • Compare glb_sel_mdl vs. glb_fin_mdl:
    • varImp
    • Prediction differences (shd be minimal ?)
  • Move glb_analytics_diag_plots to mydsutils.R: (+) Easier to debug (-) Too many glb vars used
  • Add print(ggplot.petrinet(glb_analytics_pn) + coord_flip()) at the end of every major chunk
  • Parameterize glb_analytics_pn
  • Move glb_impute_missing_data to mydsutils.R: (-) Too many glb vars used; glb_<>_df reassigned
  • Do non-glm methods handle interaction terms ?
  • f-score computation for classifiers should be summation across outcomes (not just the desired one ?)
  • Add accuracy computation to glb_dmy_mdl in predict.data.new chunk
  • Why does splitting fit.data.training.all chunk into separate chunks add an overhead of ~30 secs ? It’s not rbind b/c other chunks have lower elapsed time. Is it the number of plots ?
  • Incorporate code chunks in print_sessionInfo
  • Test against
    • projects in github.com/bdanalytics
    • lectures in jhu-datascience track

Analysis:

rm(list = ls())
set.seed(12345)
options(stringsAsFactors = FALSE)
source("~/Dropbox/datascience/R/myscript.R")
source("~/Dropbox/datascience/R/mydsutils.R")
## Loading required package: caret
## Loading required package: lattice
## Loading required package: ggplot2
source("~/Dropbox/datascience/R/myplot.R")
source("~/Dropbox/datascience/R/mypetrinet.R")
source("~/Dropbox/datascience/R/myplclust.R")
source("~/Dropbox/datascience/R/mytm.R")
# Gather all package requirements here
suppressPackageStartupMessages(require(doMC))
glbCores <- 6 # of cores on machine - 2
registerDoMC(glbCores) 

suppressPackageStartupMessages(require(caret))
require(plyr)
## Loading required package: plyr
require(dplyr)
## Loading required package: dplyr
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:plyr':
## 
##     arrange, count, desc, failwith, id, mutate, rename, summarise,
##     summarize
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
require(knitr)
## Loading required package: knitr
require(stringr)
## Loading required package: stringr
#source("dbgcaret.R")
#packageVersion("snow")
#require(sos); findFn("cosine", maxPages=2, sortby="MaxScore")

# Analysis control global variables
# Inputs
#   url/name = "<pointer>"; if url specifies a zip file, name = "<filename>"
#   sep = choose from c(NULL, "\t")
glbObsTrnFile <- list(url = "https://d37djvu3ytnwxt.cloudfront.net/asset-v1:MITx+15.071x_3+1T2016+type@asset+block/WHO.csv") 

glbObsNewFile <- #list(url = "<obsNewFileName>") # default OR
    list(splitSpecs = list(method = "copy" #select from c(NULL, "condition", "sample", "copy")
    #                      ,nRatio = 0.3 # > 0 && < 1 if method == "sample" 
    #                      ,seed = 123 # any integer or glbObsTrnPartitionSeed if method == "sample" 
    #                      ,condition = # or 'is.na(<var>)'; '<var> <condition_operator> <value>'    
                         )
       )

glbInpMerge <- NULL #: default
#     list(fnames = c("<fname1>", "<fname2>")) # files will be concatenated

glb_is_separate_newobs_dataset <- FALSE    # or TRUE
    glb_split_entity_newobs_datasets <- TRUE  # FALSE not supported - use "copy" for glbObsNewFile$splitSpecs$method

glbObsDropCondition <- NULL # : default
#   enclose in single-quotes b/c condition might include double qoutes
#       use | & ; NOT || &&    
#   '<condition>' 
    # 'grepl("^First Draft Video:", glbObsAll$Headline)'
    # '(is.na(glbObsAll[, glb_rsp_var_raw]) & grepl("Train", glbObsAll[, glbFeatsId]))'
#nrow(do.call("subset",list(glbObsAll, parse(text=paste0("!(", glbObsDropCondition, ")")))))
    
glb_obs_repartition_train_condition <- NULL # : default
#    "<condition>" 

glb_max_fitobs <- NULL # or any integer
glbObsTrnPartitionSeed <- 123 # or any integer
                         
glb_is_regression <- TRUE; glb_is_classification <- !glb_is_regression; 
    glb_is_binomial <- NULL # or TRUE or FALSE

glb_rsp_var_raw <- "LifeExpectancy"

# for classification, the response variable has to be a factor
glb_rsp_var <- glb_rsp_var_raw # or "LifeExpectancy.fctr"

# if the response factor is based on numbers/logicals e.g (0/1 OR TRUE/FALSE vs. "A"/"B"), 
#   or contains spaces (e.g. "Not in Labor Force")
#   caret predict(..., type="prob") crashes
glb_map_rsp_raw_to_var <- NULL 
# function(raw) {
#     return(raw ^ 0.5)
#     return(log(raw))
#     return(log(1 + raw))
#     return(log10(raw)) 
#     return(exp(-raw / 2))
#     ret_vals <- rep_len(NA, length(raw)); ret_vals[!is.na(raw)] <- ifelse(raw[!is.na(raw)] == 1, "Y", "N"); return(relevel(as.factor(ret_vals), ref="N"))
#     as.factor(paste0("B", raw))
#     as.factor(gsub(" ", "\\.", raw))    
#     }

#if glb_rsp_var_raw is numeric:
#print(summary(glbObsAll[, glb_rsp_var_raw]))
#glb_map_rsp_raw_to_var(tst <- c(NA, as.numeric(summary(glbObsAll[, glb_rsp_var_raw])))) 

#if glb_rsp_var_raw is character:
#print(table(glbObsAll[, glb_rsp_var_raw], useNA = "ifany"))
#print(table(glb_map_rsp_raw_to_var(tst <- glbObsAll[, glb_rsp_var_raw]), useNA = "ifany")) 

glb_map_rsp_var_to_raw <- NULL 
# function(var) {
#     return(var ^ 2.0)
#     return(exp(var))
#     return(10 ^ var) 
#     return(-log(var) * 2)
#     as.numeric(var)
#     levels(var)[as.numeric(var)]
#     gsub("\\.", " ", levels(var)[as.numeric(var)])
#     c("<=50K", " >50K")[as.numeric(var)]
#     c(FALSE, TRUE)[as.numeric(var)]
# }
#print(table(glb_map_rsp_var_to_raw(glb_map_rsp_raw_to_var(tst)), useNA = "ifany"))

if ((glb_rsp_var != glb_rsp_var_raw) && is.null(glb_map_rsp_raw_to_var))
    stop("glb_map_rsp_raw_to_var function expected")

# List info gathered for various columns
# <col_name>:   <description>; <notes>

# currently does not handle more than 1 column; consider concatenating multiple columns
# If glbFeatsId == NULL, ".rownames <- as.numeric(row.names())" is the default
glbFeatsId <- "Country" # choose from c(NULL : default, "<id_feat>") 
glbFeatsCategory <- NULL # choose from c(NULL : default, "<category_feat>")

# User-specified exclusions
glbFeatsExclude <- c(NULL
#   Feats that shd be excluded due to known causation by prediction variable
# , "<feat1", "<feat2>"
#   Feats that are linear combinations (alias in glm)
#   Feature-engineering phase -> start by excluding all features except id & category & work each one in
#   
#   Too many unique factor values
    , "Country.fctr"
#   Too many missing
    , "PrimarySchoolEnrollmentMale", "PrimarySchoolEnrollmentFemale"
    , "LiteracyRate"
    , "GNI"
#   Impute generates "singular" error
    #, "FertilityRate" 
                    ) 
if (glb_rsp_var_raw != glb_rsp_var)
    glbFeatsExclude <- union(glbFeatsExclude, glb_rsp_var_raw)                    

glbFeatsInteractionOnly <- list()
#glbFeatsInteractionOnly[["<child_feat>"]] <- "<parent_feat>"

glbFeatsDrop <- c(NULL
                # , "<feat1>", "<feat2>"
                )

glb_map_vars <- NULL # or c("<var1>", "<var2>")
glb_map_urls <- list();
# glb_map_urls[["<var1>"]] <- "<var1.url>"

glb_assign_pairs_lst <- NULL; 
# glb_assign_pairs_lst[["<var1>"]] <- list(from=c(NA),
#                                            to=c("NA.my"))
glb_assign_vars <- names(glb_assign_pairs_lst)

# Derived features; Use this mechanism to cleanse data ??? Cons: Data duplication ???
glbFeatsDerive <- list();

# glbFeatsDerive[["<feat.my.sfx>"]] <- list(
#     mapfn = function(<arg1>, <arg2>) { return(function(<arg1>, <arg2>)) } 
#   , args = c("<arg1>", "<arg2>"))
#myprint_df(data.frame(ImageId = mapfn(glbObsAll$.src, glbObsAll$.pos)))
#data.frame(ImageId = mapfn(glbObsAll$.src, glbObsAll$.pos))[7045:7055, ]

    # character
#     mapfn = function(Week) { return(substr(Week, 1, 10)) }
#     mapfn = function(Name) { return(sapply(Name, function(thsName) 
#                                             str_sub(unlist(str_split(thsName, ","))[1], 1, 1))) } 

#     mapfn = function(descriptor) { return(plyr::revalue(descriptor, c(
#         "ABANDONED BUILDING"  = "OTHER",
#         "**"                  = "**"
#                                           ))) }

#     mapfn = function(description) { mod_raw <- description;
    # This is here because it does not work if it's in txt_map_filename
#         mod_raw <- gsub(paste0(c("\n", "\211", "\235", "\317", "\333"), collapse = "|"), " ", mod_raw)
    # Don't parse for "." because of ".com"; use customized gsub for that text
#         mod_raw <- gsub("(\\w)(!|\\*|,|-|/)(\\w)", "\\1\\2 \\3", mod_raw);
    # Some state acrnoyms need context for separation e.g. 
    #   LA/L.A. could either be "Louisiana" or "LosAngeles"
        # modRaw <- gsub("\\bL\\.A\\.( |,|')", "LosAngeles\\1", modRaw);
    #   OK/O.K. could either be "Oklahoma" or "Okay"
#         modRaw <- gsub("\\bACA OK\\b", "ACA OKay", modRaw); 
#         modRaw <- gsub("\\bNow O\\.K\\.\\b", "Now OKay", modRaw);        
    #   PR/P.R. could either be "PuertoRico" or "Public Relations"        
        # modRaw <- gsub("\\bP\\.R\\. Campaign", "PublicRelations Campaign", modRaw);        
    #   VA/V.A. could either be "Virginia" or "VeteransAdministration"        
        # modRaw <- gsub("\\bthe V\\.A\\.\\:", "the VeteranAffairs:", modRaw);
    #   
    # Custom mods

#         return(mod_raw) }

    # numeric
# Create feature based on record position/id in data   
glbFeatsDerive[[".pos"]] <- list(
    mapfn = function(.rnorm) { return(1:length(.rnorm)) }       
    , args = c(".rnorm"))    
glbFeatsDerive[[".pos.y"]] <- list(
    mapfn = function(.rnorm) { return(1:length(.rnorm)) }       
    , args = c(".rnorm"))    

# Add logs of numerics that are not distributed normally
#   Derive & keep multiple transformations of the same feature, if normality is hard to achieve with just one transformation
#   Right skew: logp1; sqrt; ^ 1/3; logp1(logp1); log10; exp(-<feat>/constant)
# glbFeatsDerive[["WordCount.log1p"]] <- list(
#     mapfn = function(WordCount) { return(log1p(WordCount)) } 
#   , args = c("WordCount"))
# glbFeatsDerive[["WordCount.root2"]] <- list(
#     mapfn = function(WordCount) { return(WordCount ^ (1/2)) } 
#   , args = c("WordCount"))
# glbFeatsDerive[["WordCount.nexp"]] <- list(
#     mapfn = function(WordCount) { return(exp(-WordCount)) } 
#   , args = c("WordCount"))
#print(summary(glbObsAll$WordCount))
#print(summary(mapfn(glbObsAll$WordCount)))

# If imputation of missing data is not working ...
# glbFeatsDerive[["FertilityRate.nonNA"]] <- list(
#     mapfn = function(FertilityRate, Region) {
#         RegionMdn <- tapply(FertilityRate, Region, FUN = median, na.rm = TRUE)
# 
#         retVal <- FertilityRate
#         retVal[is.na(FertilityRate)] <- RegionMdn[Region[is.na(FertilityRate)]]
#         return(retVal)
#     }
#     , args = c("FertilityRate", "Region"))
    
#     mapfn = function(HOSPI.COST) { return(cut(HOSPI.COST, 5, breaks = c(0, 100000, 200000, 300000, 900000), labels = NULL)) }     
#     mapfn = function(Rasmussen)  { return(ifelse(sign(Rasmussen) >= 0, 1, 0)) } 
#     mapfn = function(startprice) { return(startprice ^ (1/2)) }       
#     mapfn = function(startprice) { return(log(startprice)) }   
#     mapfn = function(startprice) { return(exp(-startprice / 20)) }
#     mapfn = function(startprice) { return(scale(log(startprice))) }     
#     mapfn = function(startprice) { return(sign(sprice.predict.diff) * (abs(sprice.predict.diff) ^ (1/10))) }        

    # factor      
#     mapfn = function(PropR) { return(as.factor(ifelse(PropR >= 0.5, "Y", "N"))) }
#     mapfn = function(productline, description) { as.factor(gsub(" ", "", productline)) }
#     mapfn = function(purpose) { return(relevel(as.factor(purpose), ref="all_other")) }
#     mapfn = function(raw) { tfr_raw <- as.character(cut(raw, 5)); 
#                             tfr_raw[is.na(tfr_raw)] <- "NA.my";
#                             return(as.factor(tfr_raw)) }
#     mapfn = function(startprice.log10) { return(cut(startprice.log10, 3)) }
#     mapfn = function(startprice.log10) { return(cut(sprice.predict.diff, c(-1000, -100, -10, -1, 0, 1, 10, 100, 1000))) }    

#     , args = c("<arg1>"))
    
    # multiple args
#     mapfn = function(id, date) { return(paste(as.character(id), as.character(date), sep = "#")) }        
#     mapfn = function(PTS, oppPTS) { return(PTS - oppPTS) }
#     mapfn = function(startprice.log10.predict, startprice) {
#                  return(spdiff <- (10 ^ startprice.log10.predict) - startprice) } 
#     mapfn = function(productline, description) { as.factor(
#         paste(gsub(" ", "", productline), as.numeric(nchar(description) > 0), sep = "*")) }
#     mapfn = function(.src, .pos) { 
#         return(paste(.src, sprintf("%04d", 
#                                    ifelse(.src == "Train", .pos, .pos - 7049)
#                                    ), sep = "#")) }       

# # If glbObsAll is not sorted in the desired manner
#     mapfn=function(Week) { return(coredata(lag(zoo(orderBy(~Week, glbObsAll)$ILI), -2, na.pad=TRUE))) }
#     mapfn=function(ILI) { return(coredata(lag(zoo(ILI), -2, na.pad=TRUE))) }
#     mapfn=function(ILI.2.lag) { return(log(ILI.2.lag)) }

# glbFeatsDerive[["<var1>"]] <- glbFeatsDerive[["<var2>"]]

glb_derive_vars <- names(glbFeatsDerive)

# tst <- "descr.my"; args_lst <- NULL; for (arg in glbFeatsDerive[[tst]]$args) args_lst[[arg]] <- glbObsAll[, arg]; print(head(args_lst[[arg]])); print(head(drv_vals <- do.call(glbFeatsDerive[[tst]]$mapfn, args_lst))); 
# print(which_ix <- which(args_lst[[arg]] == 0.75)); print(drv_vals[which_ix]); 

glbFeatsDateTime <- list()
# glbFeatsDateTime[["<DateTimeFeat>"]] <- 
#     c(format = "%Y-%m-%d %H:%M:%S", timezone = "America/New_York", impute.na = TRUE, 
#       last.ctg = TRUE, poly.ctg = TRUE)

glbFeatsPrice <- NULL # or c("<price_var>")

glbFeatsImage <- list() #list(<imageFeat> = list(patchSize = 10)) # if patchSize not specified, no patch computation

glbFeatsText <- list()
Sys.setlocale("LC_ALL", "C") # For english
## [1] "C/C/C/C/C/en_US.UTF-8"
#glbFeatsText[["<TextFeature>"]] <- list(NULL,
#   ,names = myreplacePunctuation(str_to_lower(gsub(" ", "", c(NULL, 
#       <comma-separated-screened-names>
#   ))))
#   ,rareWords = myreplacePunctuation(str_to_lower(gsub(" ", "", c(NULL, 
#       <comma-separated-nonSCOWL-words>
#   ))))
#)

# Text Processing Step: custom modifications not present in txt_munge -> use glbFeatsDerive
# Text Processing Step: universal modifications
glb_txt_munge_filenames_pfx <- "<projectId>_mytxt_"

# Text Processing Step: tolower
# Text Processing Step: myreplacePunctuation
# Text Processing Step: removeWords
glb_txt_stop_words <- list()
# Remember to use unstemmed words
if (length(glbFeatsText) > 0) {
    require(tm)
    require(stringr)

    glb_txt_stop_words[["<txt_var>"]] <- sort(myreplacePunctuation(str_to_lower(gsub(" ", "", c(NULL
        # Remove any words from stopwords            
#         , setdiff(myreplacePunctuation(stopwords("english")), c("<keep_wrd1>", <keep_wrd2>"))
                                
        # Remove salutations
        ,"mr","mrs","dr","Rev"                                

        # Remove misc
        #,"th" # Happy [[:digit::]]+th birthday 

        # Remove terms present in Trn only or New only; search for "Partition post-stem"
        #   ,<comma-separated-terms>        

        # cor.y.train == NA
#         ,unlist(strsplit(paste(c(NULL
#           ,"<comma-separated-terms>"
#         ), collapse=",")

        # freq == 1; keep c("<comma-separated-terms-to-keep>")
            # ,<comma-separated-terms>

        # chisq.pval high (e.g. == 1); keep c("<comma-separated-terms-to-keep>")
            # ,<comma-separated-terms>

        # nzv.freqRatio high (e.g. >= glbFeatsNzvFreqMax); keep c("<comma-separated-terms-to-keep>")
            # ,<comma-separated-terms>        
                                            )))))
}
#orderBy(~term, glb_post_stem_words_terms_df_lst[[txtFeat]][grep("^man", glb_post_stem_words_terms_df_lst[[txtFeat]]$term), ])
#glbObsAll[glb_post_stem_words_terms_mtrx_lst[[txtFeat]][, 4866] > 0, c(glb_rsp_var, txtFeat)]

# To identify terms with a specific freq
#paste0(sort(subset(glb_post_stop_words_terms_df_lst[[txtFeat]], freq == 1)$term), collapse = ",")
#paste0(sort(subset(glb_post_stem_words_terms_df_lst[[txtFeat]], freq <= 2)$term), collapse = ",")
#subset(glb_post_stem_words_terms_df_lst[[txtFeat]], term %in% c("zinger"))

# To identify terms with a specific freq & 
#   are not stemmed together later OR is value of color.fctr (e.g. gold)
#paste0(sort(subset(glb_post_stop_words_terms_df_lst[[txtFeat]], (freq == 1) & !(term %in% c("blacked","blemish","blocked","blocks","buying","cables","careful","carefully","changed","changing","chargers","cleanly","cleared","connect","connects","connected","contains","cosmetics","default","defaulting","defective","definitely","describe","described","devices","displays","drop","drops","engravement","excellant","excellently","feels","fix","flawlessly","frame","framing","gentle","gold","guarantee","guarantees","handled","handling","having","install","iphone","iphones","keeped","keeps","known","lights","line","lining","liquid","liquidation","looking","lots","manuals","manufacture","minis","most","mostly","network","networks","noted","opening","operated","performance","performs","person","personalized","photograph","physically","placed","places","powering","pre","previously","products","protection","purchasing","returned","rotate","rotation","running","sales","second","seconds","shipped","shuts","sides","skin","skinned","sticker","storing","thats","theres","touching","unusable","update","updates","upgrade","weeks","wrapped","verified","verify") ))$term), collapse = ",")

#print(subset(glb_post_stem_words_terms_df_lst[[txtFeat]], (freq <= 2)))
#glbObsAll[which(terms_mtrx[, 229] > 0), glbFeatsText]

# To identify terms with cor.y == NA
#orderBy(~-freq+term, subset(glb_post_stop_words_terms_df_lst[[txtFeat]], is.na(cor.y)))
#paste(sort(subset(glb_post_stop_words_terms_df_lst[[txtFeat]], is.na(cor.y))[, "term"]), collapse=",")
#orderBy(~-freq+term, subset(glb_post_stem_words_terms_df_lst[[txtFeat]], is.na(cor.y)))

# To identify terms with low cor.y.abs
#head(orderBy(~cor.y.abs+freq+term, subset(glb_post_stem_words_terms_df_lst[[txtFeat]], !is.na(cor.y))), 5)

# To identify terms with high chisq.pval
#subset(glb_post_stem_words_terms_df_lst[[txtFeat]], chisq.pval > 0.99)
#paste0(sort(subset(glb_post_stem_words_terms_df_lst[[txtFeat]], (chisq.pval > 0.99) & (freq <= 10))$term), collapse=",")
#paste0(sort(subset(glb_post_stem_words_terms_df_lst[[txtFeat]], (chisq.pval > 0.9))$term), collapse=",")
#head(orderBy(~-chisq.pval+freq+term, glb_post_stem_words_terms_df_lst[[txtFeat]]), 5)
#glbObsAll[glb_post_stem_words_terms_mtrx_lst[[txtFeat]][, 68] > 0, glbFeatsText]
#orderBy(~term, glb_post_stem_words_terms_df_lst[[txtFeat]][grep("^m", glb_post_stem_words_terms_df_lst[[txtFeat]]$term), ])

# To identify terms with high nzv.freqRatio
#summary(glb_post_stem_words_terms_df_lst[[txtFeat]]$nzv.freqRatio)
#paste0(sort(setdiff(subset(glb_post_stem_words_terms_df_lst[[txtFeat]], (nzv.freqRatio >= glbFeatsNzvFreqMax) & (freq < 10) & (chisq.pval >= 0.05))$term, c( "128gb","3g","4g","gold","ipad1","ipad3","ipad4","ipadair2","ipadmini2","manufactur","spacegray","sprint","tmobil","verizon","wifion"))), collapse=",")

# To identify obs with a txt term
#tail(orderBy(~-freq+term, glb_post_stop_words_terms_df_lst[[txtFeat]]), 20)
#mydspObs(list(descr.my.contains="non"), cols=c("color", "carrier", "cellular", "storage"))
#grep("ever", dimnames(terms_stop_mtrx)$Terms)
#which(terms_stop_mtrx[, grep("ipad", dimnames(terms_stop_mtrx)$Terms)] > 0)
#glbObsAll[which(terms_stop_mtrx[, grep("16", dimnames(terms_stop_mtrx)$Terms)[1]] > 0), c(glbFeatsCategory, "storage", txtFeat)]

# Text Processing Step: screen for names # Move to glbFeatsText specs section in order of text processing steps
# glbFeatsText[["<txtFeat>"]]$names <- myreplacePunctuation(str_to_lower(gsub(" ", "", c(NULL
#         # Person names for names screening
#         ,<comma-separated-list>
#         
#         # Company names
#         ,<comma-separated-list>
#                     
#         # Product names
#         ,<comma-separated-list>
#     ))))

# glbFeatsText[["<txtFeat>"]]$rareWords <- myreplacePunctuation(str_to_lower(gsub(" ", "", c(NULL
#         # Words not in SCOWL db
#         ,<comma-separated-list>
#     ))))

# To identify char vectors post glbFeatsTextMap
#grep("six(.*)hour", glb_txt_chr_lst[[txtFeat]], ignore.case = TRUE, value = TRUE)
#grep("[S|s]ix(.*)[H|h]our", glb_txt_chr_lst[[txtFeat]], value = TRUE)

# To identify whether terms shd be synonyms
#orderBy(~term, glb_post_stop_words_terms_df_lst[[txtFeat]][grep("^moder", glb_post_stop_words_terms_df_lst[[txtFeat]]$term), ])
# term_row_df <- glb_post_stop_words_terms_df_lst[[txtFeat]][grep("^came$", glb_post_stop_words_terms_df_lst[[txtFeat]]$term), ]
# 
# cor(glb_post_stop_words_terms_mtrx_lst[[txtFeat]][glbObsAll$.lcn == "Fit", term_row_df$pos], glbObsTrn[, glb_rsp_var], use="pairwise.complete.obs")

# To identify which stopped words are "close" to a txt term
#sort(cluster_vars)

# Text Processing Step: stemDocument
# To identify stemmed txt terms
#glb_post_stop_words_terms_df_lst[[txtFeat]][grep("^la$", glb_post_stop_words_terms_df_lst[[txtFeat]]$term), ]
#orderBy(~term, glb_post_stem_words_terms_df_lst[[txtFeat]][grep("^con", glb_post_stem_words_terms_df_lst[[txtFeat]]$term), ])
#glbObsAll[which(terms_stem_mtrx[, grep("use", dimnames(terms_stem_mtrx)$Terms)[[1]]] > 0), c(glbFeatsId, "productline", txtFeat)]
#glbObsAll[which(TfIdf_stem_mtrx[, 191] > 0), c(glbFeatsId, glbFeatsCategory, txtFeat)]
#glbObsAll[which(glb_post_stop_words_terms_mtrx_lst[[txtFeat]][, 6165] > 0), c(glbFeatsId, glbFeatsCategory, txtFeat)]
#which(glbObsAll$UniqueID %in% c(11915, 11926, 12198))

# Text Processing Step: mycombineSynonyms
#   To identify which terms are associated with not -> combine "could not" & "couldn't"
#findAssocs(glb_full_DTM_lst[[txtFeat]], "not", 0.05)
#   To identify which synonyms should be combined
#orderBy(~term, glb_post_stem_words_terms_df_lst[[txtFeat]][grep("^c", glb_post_stem_words_terms_df_lst[[txtFeat]]$term), ])
chk_comb_cor <- function(syn_lst) {
#     cor(terms_stem_mtrx[glbObsAll$.src == "Train", grep("^(damag|dent|ding)$", dimnames(terms_stem_mtrx)[[2]])], glbObsTrn[, glb_rsp_var], use="pairwise.complete.obs")
    print(subset(glb_post_stem_words_terms_df_lst[[txtFeat]], term %in% syn_lst$syns))
    print(subset(get_corpus_terms(tm_map(glbFeatsTextCorpus[[txtFeat]], mycombineSynonyms, list(syn_lst), lazy=FALSE)), term == syn_lst$word))
#     cor(terms_stop_mtrx[glbObsAll$.src == "Train", grep("^(damage|dent|ding)$", dimnames(terms_stop_mtrx)[[2]])], glbObsTrn[, glb_rsp_var], use="pairwise.complete.obs")
#     cor(rowSums(terms_stop_mtrx[glbObsAll$.src == "Train", grep("^(damage|dent|ding)$", dimnames(terms_stop_mtrx)[[2]])]), glbObsTrn[, glb_rsp_var], use="pairwise.complete.obs")
}
#chk_comb_cor(syn_lst=list(word="cabl",  syns=c("cabl", "cord")))
#chk_comb_cor(syn_lst=list(word="damag",  syns=c("damag", "dent", "ding")))
#chk_comb_cor(syn_lst=list(word="dent",  syns=c("dent", "ding")))
#chk_comb_cor(syn_lst=list(word="use",  syns=c("use", "usag")))

glbFeatsTextSynonyms <- list()
# list parsed to collect glbFeatsText[[<txtFeat>]]$vldTerms
# glbFeatsTextSynonyms[["Hdln.my"]] <- list(NULL
#     # people in places
#     , list(word = "australia", syns = c("australia", "australian"))
#     , list(word = "italy", syns = c("italy", "Italian"))
#     , list(word = "newyork", syns = c("newyork", "newyorker"))    
#     , list(word = "Pakistan", syns = c("Pakistan", "Pakistani"))    
#     , list(word = "peru", syns = c("peru", "peruvian"))
#     , list(word = "qatar", syns = c("qatar", "qatari"))
#     , list(word = "scotland", syns = c("scotland", "scotish"))
#     , list(word = "Shanghai", syns = c("Shanghai", "Shanzhai"))    
#     , list(word = "venezuela", syns = c("venezuela", "venezuelan"))    
# 
#     # companies - needs to be data dependent 
#     #   - e.g. ensure BNP in this experiment/feat always refers to BNPParibas
#         
#     # general synonyms
#     , list(word = "Create", syns = c("Create","Creator")) 
#     , list(word = "cute", syns = c("cute","cutest"))     
#     , list(word = "Disappear", syns = c("Disappear","Fadeout"))     
#     , list(word = "teach", syns = c("teach", "taught"))     
#     , list(word = "theater",  syns = c("theater", "theatre", "theatres")) 
#     , list(word = "understand",  syns = c("understand", "understood"))    
#     , list(word = "weak",  syns = c("weak", "weaken", "weaker", "weakest"))
#     , list(word = "wealth",  syns = c("wealth", "wealthi"))    
#     
#     # custom synonyms (phrases)
#     
#     # custom synonyms (names)
#                                       )
#glbFeatsTextSynonyms[["<txtFeat>"]] <- list(NULL
#     , list(word="<stem1>",  syns=c("<stem1>", "<stem1_2>"))
#                                       )

for (txtFeat in names(glbFeatsTextSynonyms))
    for (entryIx in 1:length(glbFeatsTextSynonyms[[txtFeat]])) {
        glbFeatsTextSynonyms[[txtFeat]][[entryIx]]$word <-
            str_to_lower(glbFeatsTextSynonyms[[txtFeat]][[entryIx]]$word)
        glbFeatsTextSynonyms[[txtFeat]][[entryIx]]$syns <-
            str_to_lower(glbFeatsTextSynonyms[[txtFeat]][[entryIx]]$syns)        
    }        

glbFeatsTextSeed <- 181
# tm options include: check tm::weightSMART 
glb_txt_terms_control <- list( # Gather model performance & run-time stats
                    # weighting = function(x) weightSMART(x, spec = "nnn")
                    # weighting = function(x) weightSMART(x, spec = "lnn")
                    # weighting = function(x) weightSMART(x, spec = "ann")
                    # weighting = function(x) weightSMART(x, spec = "bnn")
                    # weighting = function(x) weightSMART(x, spec = "Lnn")
                    # 
                    weighting = function(x) weightSMART(x, spec = "ltn") # default
                    # weighting = function(x) weightSMART(x, spec = "lpn")                    
                    # 
                    # weighting = function(x) weightSMART(x, spec = "ltc")                    
                    # 
                    # weighting = weightBin 
                    # weighting = weightTf 
                    # weighting = weightTfIdf # : default
                # termFreq selection criteria across obs: tm default: list(global=c(1, Inf))
                    , bounds = list(global = c(1, Inf)) 
                # wordLengths selection criteria: tm default: c(3, Inf)
                    , wordLengths = c(1, Inf) 
                              ) 

glb_txt_cor_var <- glb_rsp_var # : default # or c(<feat>)

# select one from c("union.top.val.cor", "top.cor", "top.val", default: "top.chisq", "sparse")
glbFeatsTextFilter <- "top.chisq" 
glbFeatsTextTermsMax <- rep(10, length(glbFeatsText)) # :default
names(glbFeatsTextTermsMax) <- names(glbFeatsText)

# Text Processing Step: extractAssoc
glbFeatsTextAssocCor <- rep(1, length(glbFeatsText)) # :default 
names(glbFeatsTextAssocCor) <- names(glbFeatsText)

# Remember to use stemmed terms
glb_important_terms <- list()

# Text Processing Step: extractPatterns (ngrams)
glbFeatsTextPatterns <- list()
#glbFeatsTextPatterns[[<txtFeat>>]] <- list()
#glbFeatsTextPatterns[[<txtFeat>>]] <- c(metropolitan.diary.colon = "Metropolitan Diary:")

# Have to set it even if it is not used
# Properties:
#   numrows(glb_feats_df) << numrows(glbObsFit
#   Select terms that appear in at least 0.2 * O(FP/FN(glbObsOOB)) ???
#       numrows(glbObsOOB) = 1.1 * numrows(glbObsNew) ???
glb_sprs_thresholds <- NULL # or c(<txtFeat1> = 0.988, <txtFeat2> = 0.970, <txtFeat3> = 0.970)

glbFctrMaxUniqVals <- 20 # default: 20
glb_impute_na_data <- TRUE # or TRUE
glb_mice_complete.seed <- 144 # or any integer

glb_cluster <- FALSE # : default or TRUE
glb_cluster.seed <- 189 # or any integer
glb_cluster_entropy_var <- NULL # c(glb_rsp_var, as.factor(cut(glb_rsp_var, 3)), default: NULL)
glbFeatsTextClusterVarsExclude <- FALSE # default FALSE

glb_interaction_only_feats <- NULL # : default or c(<parent_feat> = "<child_feat>")

glbFeatsNzvFreqMax <- 19 # 19 : caret default
glbFeatsNzvUniqMin <- 10 # 10 : caret default

glbRFESizes <- list()
#glbRFESizes[["mdlFamily"]] <- c(4, 8, 16, 32, 64, 67, 68, 69) # Accuracy@69/70 = 0.8258

glbObsFitOutliers <- list()
# If outliers.n >= 10; consider concatenation of interaction vars
# glbObsFitOutliers[["<mdlFamily>"]] <- c(NULL
#     is.na(.rstudent)
#     max(.rstudent)
#     is.na(.dffits)
#     .hatvalues >= 0.99        
#     -38,167,642 < minmax(.rstudent) < 49,649,823    
#     , <comma-separated-<glbFeatsId>>
#                                     )
glbObsTrnOutliers <- list()
glbObsTrnOutliers[["Final"]] <- union(glbObsFitOutliers[["All.X"]],
                                c(NULL
                                ))

# influence.measures: car::outlier; rstudent; dffits; hatvalues; dfbeta; dfbetas
#mdlId <- "All.X##rcv#glm"; obs_df <- fitobs_df
#mdlId <- "RFE.X.glm"; obs_df <- fitobs_df
#mdlId <- "Final.glm"; obs_df <- trnobs_df
#mdlId <- "CSM2.X.glm"; obs_df <- fitobs_df
#print(outliers <- car::outlierTest(glb_models_lst[[mdlId]]$finalModel))
#mdlIdFamily <- paste0(head(unlist(str_split(mdlId, "\\.")), -1), collapse="."); obs_df <- dplyr::filter_(obs_df, interp(~(!(var %in% glbObsFitOutliers[[mdlIdFamily]])), var = as.name(glbFeatsId))); model_diags_df <- cbind(obs_df, data.frame(.rstudent=stats::rstudent(glb_models_lst[[mdlId]]$finalModel)), data.frame(.dffits=stats::dffits(glb_models_lst[[mdlId]]$finalModel)), data.frame(.hatvalues=stats::hatvalues(glb_models_lst[[mdlId]]$finalModel)));print(summary(model_diags_df[, c(".rstudent",".dffits",".hatvalues")])); table(cut(model_diags_df$.hatvalues, breaks=c(0.00, 0.98, 0.99, 1.00)))

#print(subset(model_diags_df, is.na(.rstudent))[, glbFeatsId])
#print(model_diags_df[which.max(model_diags_df$.rstudent), ])
#print(subset(model_diags_df, is.na(.dffits))[, glbFeatsId])
#print(model_diags_df[which.min(model_diags_df$.dffits), ])
#print(subset(model_diags_df, .hatvalues > 0.99)[, glbFeatsId])
#dffits_df <- merge(dffits_df, outliers_df, by="row.names", all.x=TRUE); row.names(dffits_df) <- dffits_df$Row.names; dffits_df <- subset(dffits_df, select=-Row.names)
#dffits_df <- merge(dffits_df, glbObsFit, by="row.names", all.x=TRUE); row.names(dffits_df) <- dffits_df$Row.names; dffits_df <- subset(dffits_df, select=-Row.names)
#subset(dffits_df, !is.na(.Bonf.p))

#mdlId <- "CSM.X.glm"; vars <- myextract_actual_feats(row.names(orderBy(reformulate(c("-", paste0(mdlId, ".imp"))), myget_feats_imp(glb_models_lst[[mdlId]])))); 
#model_diags_df <- glb_get_predictions(model_diags_df, mdlId, glb_rsp_var)
#obs_ix <- row.names(model_diags_df) %in% names(outliers$rstudent)[1]
#obs_ix <- which(is.na(model_diags_df$.rstudent))
#obs_ix <- which(is.na(model_diags_df$.dffits))
#myplot_parcoord(obs_df=model_diags_df[, c(glbFeatsId, glbFeatsCategory, ".rstudent", ".dffits", ".hatvalues", glb_rsp_var, paste0(glb_rsp_var, mdlId), vars[1:min(20, length(vars))])], obs_ix=obs_ix, id_var=glbFeatsId, category_var=glbFeatsCategory)

#model_diags_df[row.names(model_diags_df) %in% names(outliers$rstudent)[c(1:2)], ]
#ctgry_diags_df <- model_diags_df[model_diags_df[, glbFeatsCategory] %in% c("Unknown#0"), ]
#myplot_parcoord(obs_df=ctgry_diags_df[, c(glbFeatsId, glbFeatsCategory, ".rstudent", ".dffits", ".hatvalues", glb_rsp_var, "startprice.log10.predict.RFE.X.glmnet", indepVar[1:20])], obs_ix=row.names(ctgry_diags_df) %in% names(outliers$rstudent)[1], id_var=glbFeatsId, category_var=glbFeatsCategory)
#table(glbObsFit[model_diags_df[, glbFeatsCategory] %in% c("iPad1#1"), "startprice.log10.cut.fctr"])
#glbObsFit[model_diags_df[, glbFeatsCategory] %in% c("iPad1#1"), c(glbFeatsId, "startprice")]

# No outliers & .dffits == NaN
#myplot_parcoord(obs_df=model_diags_df[, c(glbFeatsId, glbFeatsCategory, glb_rsp_var, "startprice.log10.predict.RFE.X.glmnet", indepVar[1:10])], obs_ix=seq(1:nrow(model_diags_df))[is.na(model_diags_df$.dffits)], id_var=glbFeatsId, category_var=glbFeatsCategory)

# Modify mdlId to (build & extract) "<FamilyId>#<Fit|Trn>#<caretMethod>#<preProc1.preProc2>#<samplingMethod>"
glb_models_lst <- list(); glb_models_df <- data.frame()
# Regression
if (glb_is_regression) {
    glbMdlMethods <- c(NULL
        # deterministic
            #, "lm", # same as glm
            , "glm", "bayesglm", "glmnet"
            , "rpart"
        # non-deterministic
            , "gbm", "rf" 
        # Unknown
            , "nnet" , "avNNet" # runs 25 models per cv sample for tunelength=5
            , "svmLinear", "svmLinear2"
            , "svmPoly" # runs 75 models per cv sample for tunelength=5
            , "svmRadial" 
            , "earth"
            , "bagEarth" # Takes a long time
        )
} else
# Classification - Add ada (auto feature selection)
    if (glb_is_binomial)
        glbMdlMethods <- c(NULL
        # deterministic                     
            , "bagEarth" # Takes a long time        
            , "glm", "bayesglm", "glmnet"
            , "nnet"
            , "rpart"
        # non-deterministic        
            , "gbm"
            , "avNNet" # runs 25 models per cv sample for tunelength=5      
            , "rf"
        # Unknown
            , "lda", "lda2"
                # svm models crash when predict is called -> internal to kernlab it should call predict without .outcome
            , "svmLinear", "svmLinear2"
            , "svmPoly" # runs 75 models per cv sample for tunelength=5
            , "svmRadial" 
            , "earth"
        ) else
        glbMdlMethods <- c(NULL
        # deterministic
            ,"glmnet"
        # non-deterministic 
            ,"rf"       
        # Unknown
            ,"gbm","rpart"
        )

glbMdlFamilies <- list(); glb_mdl_feats_lst <- list()
# family: Choose from c("RFE.X", "CSM.X", "All.X", "Best.Interact")
#   methods: Choose from c(NULL, <method>, glbMdlMethods) 
#glbMdlFamilies[["RFE.X"]] <- c("glmnet", "glm") # non-NULL vector is mandatory
glbMdlFamilies[["All.X"]] <- c("glmnet", "glm")  # non-NULL vector is mandatory
#glbMdlFamilies[["Best.Interact"]] <- "glmnet" # non-NULL vector is mandatory

# Check if interaction features make RFE better
# glbMdlFamilies[["CSM.X"]] <- setdiff(glbMdlMethods, c("lda", "lda2")) # crashing due to category:.clusterid ??? #c("glmnet", "glm") # non-NULL list is mandatory
# glb_mdl_feats_lst[["CSM.X"]] <- c(NULL
#     , <comma-separated-features-vector>
#                                   )
# dAFeats.CSM.X %<d-% c(NULL
#     # Interaction feats up to varImp(RFE.X.glmnet) >= 50
#     , <comma-separated-features-vector>
#     , setdiff(myextract_actual_feats(predictors(rfe_fit_results)), c(NULL
#                , <comma-separated-features-vector>
#                                                                       ))    
#                                   )
# glb_mdl_feats_lst[["CSM.X"]] <- "%<d-% dAFeats.CSM.X"

glbMdlFamilies[["Final"]] <- c(NULL) # NULL vector acceptable # c("glmnet", "glm")

glbMdlAllowParallel <- list()
#glbMdlAllowParallel[["<mdlId>"]] <- FALSE

# Check if tuning parameters make fit better; make it mdlFamily customizable ?
glbMdlTuneParams <- data.frame()
# When glmnet crashes at model$grid with error: ???
glmnetTuneParams <- rbind(data.frame()
                        ,data.frame(parameter = "alpha",  vals = "0.100 0.325 0.550 0.775 1.000")
                        ,data.frame(parameter = "lambda", vals = "9.342e-02")    
                        )
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams,
#                                cbind(data.frame(mdlId = "<mdlId>"),
#                                      glmnetTuneParams))

    #avNNet    
    #   size=[1] 3 5 7 9; decay=[0] 1e-04 0.001  0.01   0.1; bag=[FALSE]; RMSE=1.3300906 

    #bagEarth
    #   degree=1 [2] 3; nprune=64 128 256 512 [1024]; RMSE=0.6486663 (up)
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
#     ,data.frame(method = "bagEarth", parameter = "nprune", vals = "256")
#     ,data.frame(method = "bagEarth", parameter = "degree", vals = "2")    
# ))

    #earth 
    #   degree=[1]; nprune=2  [9] 17 25 33; RMSE=0.1334478
    
    #gbm 
    #   shrinkage=0.05 [0.10] 0.15 0.20 0.25; n.trees=100 150 200 [250] 300; interaction.depth=[1] 2 3 4 5; n.minobsinnode=[10]; RMSE=0.2008313     
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
#     ,data.frame(method = "gbm", parameter = "shrinkage", min = 0.05, max = 0.25, by = 0.05)
#     ,data.frame(method = "gbm", parameter = "n.trees", min = 100, max = 300, by = 50)
#     ,data.frame(method = "gbm", parameter = "interaction.depth", min = 1, max = 5, by = 1)
#     ,data.frame(method = "gbm", parameter = "n.minobsinnode", min = 10, max = 10, by = 10)
#     #seq(from=0.05,  to=0.25, by=0.05)
# ))

    #glmnet
    #   alpha=0.100 [0.325] 0.550 0.775 1.000; lambda=0.0005232693 0.0024288010 0.0112734954 [0.0523269304] 0.2428800957; RMSE=0.6164891
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
#     ,data.frame(method = "glmnet", parameter = "alpha", vals = "0.550 0.775 0.8875 0.94375 1.000")
#     ,data.frame(method = "glmnet", parameter = "lambda", vals = "9.858855e-05 0.0001971771 0.0009152152 0.0042480525 0.0197177130")    
# ))

    #nnet    
    #   size=3 5 [7] 9 11; decay=0.0001 0.001 0.01 [0.1] 0.2; RMSE=0.9287422
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
#     ,data.frame(method = "nnet", parameter = "size", vals = "3 5 7 9 11")
#     ,data.frame(method = "nnet", parameter = "decay", vals = "0.0001 0.0010 0.0100 0.1000 0.2000")    
# ))

    #rf # Don't bother; results are not deterministic
    #       mtry=2  35  68 [101] 134; RMSE=0.1339974
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
#     ,data.frame(method = "rf", parameter = "mtry", vals = "2 5 9 13 17")
# ))

    #rpart 
    #   cp=0.020 [0.025] 0.030 0.035 0.040; RMSE=0.1770237
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()    
#     ,data.frame(method = "rpart", parameter = "cp", vals = "0.004347826 0.008695652 0.017391304 0.021739130 0.034782609")
# ))
    
    #svmLinear
    #   C=0.01 0.05 [0.10] 0.50 1.00 2.00 3.00 4.00; RMSE=0.1271318; 0.1296718
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
#     ,data.frame(method = "svmLinear", parameter = "C", vals = "0.01 0.05 0.1 0.5 1")
# ))

    #svmLinear2    
    #   cost=0.0625 0.1250 [0.25] 0.50 1.00; RMSE=0.1276354 
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
#     ,data.frame(method = "svmLinear2", parameter = "cost", vals = "0.0625 0.125 0.25 0.5 1")
# ))

    #svmPoly    
    #   degree=[1] 2 3 4 5; scale=0.01 0.05 [0.1] 0.5 1; C=0.50 1.00 [2.00] 3.00 4.00; RMSE=0.1276130
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
#     ,data.frame(method="svmPoly", parameter="degree", min=1, max=5, by=1) #seq(1, 5, 1)
#     ,data.frame(method="svmPoly", parameter="scale", vals="0.01, 0.05, 0.1, 0.5, 1")
#     ,data.frame(method="svmPoly", parameter="C", vals="0.50, 1.00, 2.00, 3.00, 4.00")    
# ))

    #svmRadial
    #   sigma=[0.08674323]; C=0.25 0.50 1.00 [2.00] 4.00; RMSE=0.1614957
    
#glb2Sav(); all.equal(sav_models_df, glb_models_df)
    
glb_preproc_methods <- NULL
#     c("YeoJohnson", "center.scale", "range", "pca", "ica", "spatialSign")

# Baseline prediction model feature(s)
glb_Baseline_mdl_var <- NULL # or c("<feat>")

glbMdlMetric_terms <- NULL # or matrix(c(
#                               0,1,2,3,4,
#                               2,0,1,2,3,
#                               4,2,0,1,2,
#                               6,4,2,0,1,
#                               8,6,4,2,0
#                           ), byrow=TRUE, nrow=5)
glbMdlMetricSummary <- NULL # or "<metric_name>"
glbMdlMetricMaximize <- NULL # or FALSE (TRUE is not the default for both classification & regression) 
glbMdlMetricSummaryFn <- NULL # or function(data, lev=NULL, model=NULL) {
#     confusion_mtrx <- t(as.matrix(confusionMatrix(data$pred, data$obs)))
#     #print(confusion_mtrx)
#     #print(confusion_mtrx * glbMdlMetric_terms)
#     metric <- sum(confusion_mtrx * glbMdlMetric_terms) / nrow(data)
#     names(metric) <- glbMdlMetricSummary
#     return(metric)
# }

glbMdlCheckRcv <- FALSE # Turn it on when needed; otherwise takes long time
glb_rcv_n_folds <- 3 # or NULL
glb_rcv_n_repeats <- 3 # or NULL

glb_clf_proba_threshold <- NULL # 0.5

# Model selection criteria
if (glb_is_regression)
    glbMdlMetricsEval <- c("min.RMSE.OOB", "max.R.sq.OOB", "max.Adj.R.sq.fit", "min.RMSE.fit")
    #glbMdlMetricsEval <- c("min.RMSE.fit", "max.R.sq.fit", "max.Adj.R.sq.fit")    
if (glb_is_classification) {
    if (glb_is_binomial)
        glbMdlMetricsEval <- 
            c("max.Accuracy.OOB", "max.AUCROCR.OOB", "max.AUCpROC.OOB", "min.aic.fit", "max.Accuracy.fit") else        
        glbMdlMetricsEval <- c("max.Accuracy.OOB", "max.Kappa.OOB")
}

# select from NULL [no ensemble models], "auto" [all models better than MFO or Baseline], c(mdl_ids in glb_models_lst) [Typically top-rated models in auto]
glb_mdl_ensemble <- NULL
#     "%<d-% setdiff(mygetEnsembleAutoMdlIds(), 'CSM.X.rf')" 
#     c(<comma-separated-mdlIds>
#      )

# Only for classifications; for regressions remove "(.*)\\.prob" form the regex
# tmp_fitobs_df <- glbObsFit[, grep(paste0("^", gsub(".", "\\.", mygetPredictIds$value, fixed = TRUE), "CSM\\.X\\.(.*)\\.prob"), names(glbObsFit), value = TRUE)]; cor_mtrx <- cor(tmp_fitobs_df); cor_vctr <- sort(cor_mtrx[row.names(orderBy(~-Overall, varImp(glb_models_lst[["Ensemble.repeatedcv.glmnet"]])$imp))[1], ]); summary(cor_vctr); cor_vctr
#ntv.glm <- glm(reformulate(indepVar, glb_rsp_var), family = "binomial", data = glbObsFit)
#step.glm <- step(ntv.glm)

glb_sel_mdl_id <- "All.X##rcv#glmnet" #select from c(NULL, "All.X##rcv#glmnet", "RFE.X##rcv#glmnet", <mdlId>)
glb_fin_mdl_id <- NULL #select from c(NULL, glb_sel_mdl_id)

glb_dsp_cols <- c(".pos", glbFeatsId, glbFeatsCategory, glb_rsp_var
#               List critical cols excl. above
                  )

# Output specs
# lclgetfltout_df <- function(obsout_df) {
#     require(tidyr)
#     obsout_df <- obsout_df %>%
#         tidyr::separate("ImageId.x.y", c(".src", ".pos", "x", "y"), 
#                         sep = "#", remove = TRUE, extra = "merge")
#     # mnm prefix stands for max_n_mean
#     mnmout_df <- obsout_df %>%
#         dplyr::group_by(.pos) %>%
#         #dplyr::top_n(1, Probability1) %>% # Score = 3.9426         
#         #dplyr::top_n(2, Probability1) %>% # Score = ???; weighted = 3.94254;         
#         #dplyr::top_n(3, Probability1) %>% # Score = 3.9418; weighted = 3.94169; 
#         dplyr::top_n(4, Probability1) %>% # Score = ???; weighted = 3.94149;        
#         #dplyr::top_n(5, Probability1) %>% # Score = 3.9421; weighted = 3.94178
#     
#         # dplyr::summarize(xMeanN = mean(as.numeric(x)), yMeanN = mean(as.numeric(y)))
#         # dplyr::summarize(xMeanN = weighted.mean(as.numeric(x), Probability1), yMeanN = mean(as.numeric(y)))
#         # dplyr::summarize(xMeanN = weighted.mean(as.numeric(x), c(Probability1, 0.2357323, 0.2336925)), yMeanN = mean(as.numeric(y)))    
#         # dplyr::summarize(xMeanN = weighted.mean(as.numeric(x), c(Probability1)), yMeanN = mean(as.numeric(y)))
#         dplyr::summarize(xMeanN = weighted.mean(as.numeric(x), c(Probability1)), 
#                          yMeanN = weighted.mean(as.numeric(y), c(Probability1)))  
#     
#     maxout_df <- obsout_df %>%
#         dplyr::group_by(.pos) %>%
#         dplyr::summarize(maxProb1 = max(Probability1))
#     fltout_df <- merge(maxout_df, obsout_df, 
#                        by.x = c(".pos", "maxProb1"), by.y = c(".pos", "Probability1"),
#                        all.x = TRUE)
#     fmnout_df <- merge(fltout_df, mnmout_df, 
#                        by.x = c(".pos"), by.y = c(".pos"),
#                        all.x = TRUE)
#     return(fmnout_df)
# }
glbObsOut <- list(NULL
        # glbFeatsId will be the first output column, by default
        ,vars = list()
#         ,mapFn = function(obsout_df) {
#                   }
                  )
#obsout_df <- savobsout_df
# glbObsOut$mapFn <- function(obsout_df) {
#     txfout_df <- dplyr::select(obsout_df, -.pos.y) %>%
#         dplyr::mutate(
#             lunch     = levels(glbObsTrn[, "lunch"    ])[
#                        round(mean(as.numeric(glbObsTrn[, "lunch"    ])), 0)],
#             dinner    = levels(glbObsTrn[, "dinner"   ])[
#                        round(mean(as.numeric(glbObsTrn[, "dinner"   ])), 0)],
#             reserve   = levels(glbObsTrn[, "reserve"  ])[
#                        round(mean(as.numeric(glbObsTrn[, "reserve"  ])), 0)],
#             outdoor   = levels(glbObsTrn[, "outdoor"  ])[
#                        round(mean(as.numeric(glbObsTrn[, "outdoor"  ])), 0)],
#             expensive = levels(glbObsTrn[, "expensive"])[
#                        round(mean(as.numeric(glbObsTrn[, "expensive"])), 0)],
#             liquor    = levels(glbObsTrn[, "liquor"   ])[
#                        round(mean(as.numeric(glbObsTrn[, "liquor"   ])), 0)],
#             table     = levels(glbObsTrn[, "table"    ])[
#                        round(mean(as.numeric(glbObsTrn[, "table"    ])), 0)],
#             classy    = levels(glbObsTrn[, "classy"   ])[
#                        round(mean(as.numeric(glbObsTrn[, "classy"   ])), 0)],
#             kids      = levels(glbObsTrn[, "kids"     ])[
#                        round(mean(as.numeric(glbObsTrn[, "kids"     ])), 0)]
#                       )
#     
#     print("ObsNew output class tables:")
#     print(sapply(c("lunch","dinner","reserve","outdoor",
#                    "expensive","liquor","table",
#                    "classy","kids"), 
#                  function(feat) table(txfout_df[, feat], useNA = "ifany")))
#     
#     txfout_df <- txfout_df %>%
#         dplyr::mutate(labels = "") %>%
#         dplyr::mutate(labels = 
#     ifelse(lunch     != "-1", paste(labels, lunch    ), labels)) %>%
#         dplyr::mutate(labels = 
#     ifelse(dinner    != "-1", paste(labels, dinner   ), labels)) %>%
#         dplyr::mutate(labels = 
#     ifelse(reserve   != "-1", paste(labels, reserve  ), labels)) %>%
#         dplyr::mutate(labels = 
#     ifelse(outdoor   != "-1", paste(labels, outdoor  ), labels)) %>%
#         dplyr::mutate(labels =         
#     ifelse(expensive != "-1", paste(labels, expensive), labels)) %>%
#         dplyr::mutate(labels =         
#     ifelse(liquor    != "-1", paste(labels, liquor   ), labels)) %>%
#         dplyr::mutate(labels =         
#     ifelse(table     != "-1", paste(labels, table    ), labels)) %>%
#         dplyr::mutate(labels =         
#     ifelse(classy    != "-1", paste(labels, classy   ), labels)) %>%
#         dplyr::mutate(labels =         
#     ifelse(kids      != "-1", paste(labels, kids     ), labels)) %>%
#         dplyr::select(business_id, labels)
#     return(txfout_df)
# }
#if (!is.null(glbObsOut$mapFn)) obsout_df <- glbObsOut$mapFn(obsout_df); print(head(obsout_df))

glb_out_obs <- NULL # select from c(NULL : default to "new", "all", "new", "trn")

if (glb_is_classification && glb_is_binomial) {
    glbObsOut$vars[["Probability1"]] <- 
        "%<d-% glbObsNew[, mygetPredictIds(glb_rsp_var, glb_fin_mdl_id)$prob]" 
#     glbObsOut$vars[[glb_rsp_var_raw]] <- 
#         "%<d-% glb_map_rsp_var_to_raw(glbObsNew[, 
#                                             mygetPredictIds(glb_rsp_var, glb_fin_mdl_id)$value])"         
} else {
#     glbObsOut$vars[[glbFeatsId]] <- 
#         "%<d-% as.integer(gsub('Test#', '', glbObsNew[, glbFeatsId]))"
    glbObsOut$vars[[glb_rsp_var]] <- 
        "%<d-% glbObsNew[, mygetPredictIds(glb_rsp_var, glb_fin_mdl_id)$value]"
#     for (outVar in setdiff(glbFeatsExcludeLcl, glb_rsp_var_raw))
#         glbObsOut$vars[[outVar]] <- 
#             paste0("%<d-% mean(glbObsAll[, \"", outVar, "\"], na.rm = TRUE)")
}    
# glbObsOut$vars[[glb_rsp_var_raw]] <- glb_rsp_var_raw
# glbObsOut$vars[[paste0(head(unlist(strsplit(mygetPredictIds$value, "")), -1), collapse = "")]] <-

glbOutStackFnames <- NULL #: default
    # c("ebayipads_txt_assoc1_out_bid1_stack.csv") # manual stack
    # c("ebayipads_finmdl_bid1_out_nnet_1.csv") # universal stack

glbOut <- list(pfx = "<scriptName>_")
# lclImageSampleSeed <- 129
glbOutDataVizFname <- NULL # choose from c(NULL, "<projectId>_obsall.csv")


glbChunks <- list(labels = c("set_global_options_wd","set_global_options"
    ,"import.data","inspect.data","scrub.data","transform.data"
    ,"extract.features"
        ,"extract.features.datetime","extract.features.image","extract.features.price"
        ,"extract.features.text","extract.features.string"  
        ,"extract.features.end"
    ,"manage.missing.data","cluster.data","partition.data.training","select.features"
    ,"fit.models_0","fit.models_1","fit.models_2","fit.models_3"
    ,"fit.data.training_0","fit.data.training_1"
    ,"predict.data.new"         
    ,"display.session.info"))
# To ensure that all chunks in this script are in glbChunks
if (!is.null(chkChunksLabels <- knitr::all_labels()) && # knitr::all_labels() doesn't work in console runs
    !identical(chkChunksLabels, glbChunks$labels)) {
    print(sprintf("setdiff(chkChunksLabels, glbChunks$labels): %s", 
                  setdiff(chkChunksLabels, glbChunks$labels)))    
    print(sprintf("setdiff(glbChunks$labels, chkChunksLabels): %s", 
                  setdiff(glbChunks$labels, chkChunksLabels)))    
}

glbChunks[["first"]] <- NULL #default: script will load envir from previous chunk
glbChunks[["last"]] <- NULL #"extract.features.end" #NULL #default: script will save envir at end of this chunk 
#mysavChunk(glbOut$pfx, glbChunks[["last"]])

# Inspect max OOB FP
#chkObsOOB <- subset(glbObsOOB, !label.fctr.All.X..rcv.glmnet.is.acc)
#chkObsOOBFP <- subset(chkObsOOB, label.fctr.All.X..rcv.glmnet == "left_eye_center") %>% dplyr::mutate(Probability1 = label.fctr.All.X..rcv.glmnet.prob) %>% select(-.src, -.pos, -x, -y) %>% lclgetfltout_df() %>% mutate(obj.distance = (((as.numeric(x) - left_eye_center_x.int) ^ 2) + ((as.numeric(y) - left_eye_center_y.int) ^ 2)) ^ 0.5) %>% dplyr::top_n(5, obj.distance) %>% dplyr::top_n(5, -patch.cor)
#
#newImgObs <- glbObsNew[(glbObsNew$ImageId == "Test#0001"), ]; print(newImgObs[which.max(newImgObs$label.fctr.Final..rcv.glmnet.prob), ])
#OOBImgObs <- glbObsOOB[(glbObsOOB$ImageId == "Train#0003"), ]; print(OOBImgObs[which.max(OOBImgObs$label.fctr.All.X..rcv.glmnet.prob), ])

#load("<scriptName>_extract.features.end.RData", verbose = TRUE)
#mygetImage(which(glbObsAll[, glbFeatsId] == "Train#0003"), names(glbFeatsImage)[1], plot = TRUE, featHighlight = c("left_eye_center_x", "left_eye_center_y"), ovrlHighlight = c(66, 35))

# Depict process
glb_analytics_pn <- petrinet(name = "glb_analytics_pn",
                        trans_df = data.frame(id = 1:6,
    name = c("data.training.all","data.new",
           "model.selected","model.final",
           "data.training.all.prediction","data.new.prediction"),
    x=c(   -5,-5,-15,-25,-25,-35),
    y=c(   -5, 5,  0,  0, -5,  5)
                        ),
                        places_df=data.frame(id=1:4,
    name=c("bgn","fit.data.training.all","predict.data.new","end"),
    x=c(   -0,   -20,                    -30,               -40),
    y=c(    0,     0,                      0,                 0),
    M0=c(   3,     0,                      0,                 0)
                        ),
                        arcs_df = data.frame(
    begin = c("bgn","bgn","bgn",        
            "data.training.all","model.selected","fit.data.training.all",
            "fit.data.training.all","model.final",    
            "data.new","predict.data.new",
            "data.training.all.prediction","data.new.prediction"),
    end   = c("data.training.all","data.new","model.selected",
            "fit.data.training.all","fit.data.training.all","model.final",
            "data.training.all.prediction","predict.data.new",
            "predict.data.new","data.new.prediction",
            "end","end")
                        ))
#print(ggplot.petrinet(glb_analytics_pn))
print(ggplot.petrinet(glb_analytics_pn) + coord_flip())
## Loading required package: grid

glb_analytics_avl_objs <- NULL

glb_chunks_df <- myadd_chunk(NULL, "import.data")
##         label step_major step_minor label_minor   bgn end elapsed
## 1 import.data          1          0           0 5.756  NA      NA

Step 1.0: import data

chunk option: eval=

## [1] "Reading file ./data/WHO.csv..."
## [1] "dimensions of data in ./data/WHO.csv: 194 rows x 13 cols"
##               Country                Region Population Under15 Over60
## 1         Afghanistan Eastern Mediterranean      29825   47.42   3.82
## 2             Albania                Europe       3162   21.33  14.93
## 3             Algeria                Africa      38482   27.42   7.17
## 4             Andorra                Europe         78   15.20  22.86
## 5              Angola                Africa      20821   47.58   3.84
## 6 Antigua and Barbuda              Americas         89   25.96  12.35
##   FertilityRate LifeExpectancy ChildMortality CellularSubscribers
## 1          5.40             60           98.5               54.26
## 2          1.75             74           16.7               96.39
## 3          2.83             73           20.0               98.99
## 4            NA             82            3.2               75.49
## 5          6.10             51          163.5               48.38
## 6          2.12             75            9.9              196.41
##   LiteracyRate   GNI PrimarySchoolEnrollmentMale
## 1           NA  1140                          NA
## 2           NA  8820                          NA
## 3           NA  8310                        98.2
## 4           NA    NA                        78.4
## 5         70.1  5230                        93.1
## 6         99.0 17900                        91.1
##   PrimarySchoolEnrollmentFemale
## 1                            NA
## 2                            NA
## 3                          96.4
## 4                          79.4
## 5                          78.2
## 6                          84.5
##                 Country          Region Population Under15 Over60
## 7             Argentina        Americas      41087   24.42  14.97
## 29             Cambodia Western Pacific      14865   31.23   7.67
## 99            Lithuania          Europe       3028   15.13  20.57
## 140 Republic of Moldova          Europe       3514   16.52  16.72
## 141             Romania          Europe      21755   15.05  20.66
## 191            Viet Nam Western Pacific      90796   22.87   9.32
##     FertilityRate LifeExpectancy ChildMortality CellularSubscribers
## 7            2.20             76           14.2              134.92
## 29           2.93             65           39.7               96.17
## 99           1.49             74            5.4              151.30
## 140          1.47             71           17.6              104.80
## 141          1.39             74           12.2              109.16
## 191          1.79             75           23.0              143.39
##     LiteracyRate   GNI PrimarySchoolEnrollmentMale
## 7           97.8 17130                          NA
## 29            NA  2230                        96.4
## 99          99.7 19640                        95.6
## 140         98.5  3640                        90.1
## 141         97.7 15120                        87.9
## 191         93.2  3250                          NA
##     PrimarySchoolEnrollmentFemale
## 7                              NA
## 29                           95.4
## 99                           95.8
## 140                          90.1
## 141                          87.3
## 191                            NA
##                                Country                Region Population
## 189                            Vanuatu       Western Pacific        247
## 190 Venezuela (Bolivarian Republic of)              Americas      29955
## 191                           Viet Nam       Western Pacific      90796
## 192                              Yemen Eastern Mediterranean      23852
## 193                             Zambia                Africa      14075
## 194                           Zimbabwe                Africa      13724
##     Under15 Over60 FertilityRate LifeExpectancy ChildMortality
## 189   37.37   6.02          3.46             72           17.9
## 190   28.84   9.17          2.44             75           15.3
## 191   22.87   9.32          1.79             75           23.0
## 192   40.72   4.54          4.35             64           60.0
## 193   46.73   3.95          5.77             55           88.5
## 194   40.24   5.68          3.64             54           89.8
##     CellularSubscribers LiteracyRate   GNI PrimarySchoolEnrollmentMale
## 189               55.76         82.6  4330                          NA
## 190               97.78           NA 12430                        94.7
## 191              143.39         93.2  3250                          NA
## 192               47.05         63.9  2170                        85.5
## 193               60.59         71.2  1490                        91.4
## 194               72.13         92.2    NA                          NA
##     PrimarySchoolEnrollmentFemale
## 189                            NA
## 190                          95.1
## 191                            NA
## 192                          70.5
## 193                          93.9
## 194                            NA
## 'data.frame':    194 obs. of  13 variables:
##  $ Country                      : chr  "Afghanistan" "Albania" "Algeria" "Andorra" ...
##  $ Region                       : chr  "Eastern Mediterranean" "Europe" "Africa" "Europe" ...
##  $ Population                   : int  29825 3162 38482 78 20821 89 41087 2969 23050 8464 ...
##  $ Under15                      : num  47.4 21.3 27.4 15.2 47.6 ...
##  $ Over60                       : num  3.82 14.93 7.17 22.86 3.84 ...
##  $ FertilityRate                : num  5.4 1.75 2.83 NA 6.1 2.12 2.2 1.74 1.89 1.44 ...
##  $ LifeExpectancy               : int  60 74 73 82 51 75 76 71 82 81 ...
##  $ ChildMortality               : num  98.5 16.7 20 3.2 163.5 ...
##  $ CellularSubscribers          : num  54.3 96.4 99 75.5 48.4 ...
##  $ LiteracyRate                 : num  NA NA NA NA 70.1 99 97.8 99.6 NA NA ...
##  $ GNI                          : num  1140 8820 8310 NA 5230 ...
##  $ PrimarySchoolEnrollmentMale  : num  NA NA 98.2 78.4 93.1 91.1 NA NA 96.9 NA ...
##  $ PrimarySchoolEnrollmentFemale: num  NA NA 96.4 79.4 78.2 84.5 NA NA 97.5 NA ...
##  - attr(*, "comment")= chr "glbObsTrn"
## NULL
##               Country                Region Population Under15 Over60
## 1         Afghanistan Eastern Mediterranean      29825   47.42   3.82
## 2             Albania                Europe       3162   21.33  14.93
## 3             Algeria                Africa      38482   27.42   7.17
## 4             Andorra                Europe         78   15.20  22.86
## 5              Angola                Africa      20821   47.58   3.84
## 6 Antigua and Barbuda              Americas         89   25.96  12.35
##   FertilityRate LifeExpectancy ChildMortality CellularSubscribers
## 1          5.40             60           98.5               54.26
## 2          1.75             74           16.7               96.39
## 3          2.83             73           20.0               98.99
## 4            NA             82            3.2               75.49
## 5          6.10             51          163.5               48.38
## 6          2.12             75            9.9              196.41
##   LiteracyRate   GNI PrimarySchoolEnrollmentMale
## 1           NA  1140                          NA
## 2           NA  8820                          NA
## 3           NA  8310                        98.2
## 4           NA    NA                        78.4
## 5         70.1  5230                        93.1
## 6         99.0 17900                        91.1
##   PrimarySchoolEnrollmentFemale
## 1                            NA
## 2                            NA
## 3                          96.4
## 4                          79.4
## 5                          78.2
## 6                          84.5
##        Country                Region Population Under15 Over60
## 1  Afghanistan Eastern Mediterranean      29825   47.42   3.82
## 34        Chad                Africa      12448   48.52   3.80
## 75    Honduras              Americas       7936   35.72   6.41
## 76     Hungary                Europe       9976   14.62  23.41
## 77     Iceland                Europe        326   20.71  17.62
## 89       Kenya                Africa      43178   42.37   4.25
##    FertilityRate LifeExpectancy ChildMortality CellularSubscribers
## 1           5.40             60           98.5               54.26
## 34          6.49             51          149.8               31.80
## 75          3.10             74           22.9              103.97
## 76          1.38             75            6.2              117.30
## 77          2.11             82            2.3              106.08
## 89          4.54             60           72.9               67.49
##    LiteracyRate   GNI PrimarySchoolEnrollmentMale
## 1            NA  1140                          NA
## 34         34.5  1360                          NA
## 75         84.8  3820                        94.8
## 76         99.0 20310                        97.8
## 77           NA 31020                        98.8
## 89         87.4  1710                          NA
##    PrimarySchoolEnrollmentFemale
## 1                             NA
## 34                            NA
## 75                          97.0
## 76                          98.3
## 77                          99.2
## 89                            NA
##                                Country                Region Population
## 189                            Vanuatu       Western Pacific        247
## 190 Venezuela (Bolivarian Republic of)              Americas      29955
## 191                           Viet Nam       Western Pacific      90796
## 192                              Yemen Eastern Mediterranean      23852
## 193                             Zambia                Africa      14075
## 194                           Zimbabwe                Africa      13724
##     Under15 Over60 FertilityRate LifeExpectancy ChildMortality
## 189   37.37   6.02          3.46             72           17.9
## 190   28.84   9.17          2.44             75           15.3
## 191   22.87   9.32          1.79             75           23.0
## 192   40.72   4.54          4.35             64           60.0
## 193   46.73   3.95          5.77             55           88.5
## 194   40.24   5.68          3.64             54           89.8
##     CellularSubscribers LiteracyRate   GNI PrimarySchoolEnrollmentMale
## 189               55.76         82.6  4330                          NA
## 190               97.78           NA 12430                        94.7
## 191              143.39         93.2  3250                          NA
## 192               47.05         63.9  2170                        85.5
## 193               60.59         71.2  1490                        91.4
## 194               72.13         92.2    NA                          NA
##     PrimarySchoolEnrollmentFemale
## 189                            NA
## 190                          95.1
## 191                            NA
## 192                          70.5
## 193                          93.9
## 194                            NA
## 'data.frame':    194 obs. of  13 variables:
##  $ Country                      : chr  "Afghanistan" "Albania" "Algeria" "Andorra" ...
##  $ Region                       : chr  "Eastern Mediterranean" "Europe" "Africa" "Europe" ...
##  $ Population                   : int  29825 3162 38482 78 20821 89 41087 2969 23050 8464 ...
##  $ Under15                      : num  47.4 21.3 27.4 15.2 47.6 ...
##  $ Over60                       : num  3.82 14.93 7.17 22.86 3.84 ...
##  $ FertilityRate                : num  5.4 1.75 2.83 NA 6.1 2.12 2.2 1.74 1.89 1.44 ...
##  $ LifeExpectancy               : int  60 74 73 82 51 75 76 71 82 81 ...
##  $ ChildMortality               : num  98.5 16.7 20 3.2 163.5 ...
##  $ CellularSubscribers          : num  54.3 96.4 99 75.5 48.4 ...
##  $ LiteracyRate                 : num  NA NA NA NA 70.1 99 97.8 99.6 NA NA ...
##  $ GNI                          : num  1140 8820 8310 NA 5230 ...
##  $ PrimarySchoolEnrollmentMale  : num  NA NA 98.2 78.4 93.1 91.1 NA NA 96.9 NA ...
##  $ PrimarySchoolEnrollmentFemale: num  NA NA 96.4 79.4 78.2 84.5 NA NA 97.5 NA ...
##  - attr(*, "comment")= chr "glbObsNew"
##               Country                Region Population Under15 Over60
## 1         Afghanistan Eastern Mediterranean      29825   47.42   3.82
## 2             Albania                Europe       3162   21.33  14.93
## 3             Algeria                Africa      38482   27.42   7.17
## 4             Andorra                Europe         78   15.20  22.86
## 5              Angola                Africa      20821   47.58   3.84
## 6 Antigua and Barbuda              Americas         89   25.96  12.35
##   FertilityRate LifeExpectancy ChildMortality CellularSubscribers
## 1          5.40             60           98.5               54.26
## 2          1.75             74           16.7               96.39
## 3          2.83             73           20.0               98.99
## 4            NA             82            3.2               75.49
## 5          6.10             51          163.5               48.38
## 6          2.12             75            9.9              196.41
##   LiteracyRate   GNI PrimarySchoolEnrollmentMale
## 1           NA  1140                          NA
## 2           NA  8820                          NA
## 3           NA  8310                        98.2
## 4           NA    NA                        78.4
## 5         70.1  5230                        93.1
## 6         99.0 17900                        91.1
##   PrimarySchoolEnrollmentFemale
## 1                            NA
## 2                            NA
## 3                          96.4
## 4                          79.4
## 5                          78.2
## 6                          84.5
##                         Country          Region Population Under15 Over60
## 63                        Gabon          Africa       1633   38.49   7.38
## 88                   Kazakhstan          Europe      16271   25.46  10.04
## 122                 New Zealand Western Pacific       4460   20.26  19.01
## 135                 Philippines Western Pacific      96707   34.53   6.21
## 185 United Republic of Tanzania          Africa      47783   44.85   4.89
## 194                    Zimbabwe          Africa      13724   40.24   5.68
##     FertilityRate LifeExpectancy ChildMortality CellularSubscribers
## 63           4.18             62           62.0              117.32
## 88           2.52             67           18.7              155.74
## 122          2.10             81            5.7              109.19
## 135          3.11             69           29.8               99.30
## 185          5.36             59           54.0               55.53
## 194          3.64             54           89.8               72.13
##     LiteracyRate   GNI PrimarySchoolEnrollmentMale
## 63          88.4 13740                          NA
## 88          99.7 11250                          NA
## 122           NA    NA                        99.3
## 135           NA  4140                          NA
## 185         73.2  1500                          NA
## 194         92.2    NA                          NA
##     PrimarySchoolEnrollmentFemale
## 63                             NA
## 88                             NA
## 122                          99.6
## 135                            NA
## 185                            NA
## 194                            NA
##                                Country                Region Population
## 189                            Vanuatu       Western Pacific        247
## 190 Venezuela (Bolivarian Republic of)              Americas      29955
## 191                           Viet Nam       Western Pacific      90796
## 192                              Yemen Eastern Mediterranean      23852
## 193                             Zambia                Africa      14075
## 194                           Zimbabwe                Africa      13724
##     Under15 Over60 FertilityRate LifeExpectancy ChildMortality
## 189   37.37   6.02          3.46             72           17.9
## 190   28.84   9.17          2.44             75           15.3
## 191   22.87   9.32          1.79             75           23.0
## 192   40.72   4.54          4.35             64           60.0
## 193   46.73   3.95          5.77             55           88.5
## 194   40.24   5.68          3.64             54           89.8
##     CellularSubscribers LiteracyRate   GNI PrimarySchoolEnrollmentMale
## 189               55.76         82.6  4330                          NA
## 190               97.78           NA 12430                        94.7
## 191              143.39         93.2  3250                          NA
## 192               47.05         63.9  2170                        85.5
## 193               60.59         71.2  1490                        91.4
## 194               72.13         92.2    NA                          NA
##     PrimarySchoolEnrollmentFemale
## 189                            NA
## 190                          95.1
## 191                            NA
## 192                          70.5
## 193                          93.9
## 194                            NA
## 'data.frame':    194 obs. of  13 variables:
##  $ Country                      : chr  "Afghanistan" "Albania" "Algeria" "Andorra" ...
##  $ Region                       : chr  "Eastern Mediterranean" "Europe" "Africa" "Europe" ...
##  $ Population                   : int  29825 3162 38482 78 20821 89 41087 2969 23050 8464 ...
##  $ Under15                      : num  47.4 21.3 27.4 15.2 47.6 ...
##  $ Over60                       : num  3.82 14.93 7.17 22.86 3.84 ...
##  $ FertilityRate                : num  5.4 1.75 2.83 NA 6.1 2.12 2.2 1.74 1.89 1.44 ...
##  $ LifeExpectancy               : int  60 74 73 82 51 75 76 71 82 81 ...
##  $ ChildMortality               : num  98.5 16.7 20 3.2 163.5 ...
##  $ CellularSubscribers          : num  54.3 96.4 99 75.5 48.4 ...
##  $ LiteracyRate                 : num  NA NA NA NA 70.1 99 97.8 99.6 NA NA ...
##  $ GNI                          : num  1140 8820 8310 NA 5230 ...
##  $ PrimarySchoolEnrollmentMale  : num  NA NA 98.2 78.4 93.1 91.1 NA NA 96.9 NA ...
##  $ PrimarySchoolEnrollmentFemale: num  NA NA 96.4 79.4 78.2 84.5 NA NA 97.5 NA ...
##  - attr(*, "comment")= chr "glbObsTrn"
## Warning: glbObsTrn same as glbObsAll
## Warning: glbObsNew same as glbObsAll
## [1] "Creating new feature: .pos..."
## [1] "Creating new feature: .pos.y..."
## [1] "Partition stats:"
## Loading required package: sqldf
## Loading required package: gsubfn
## Loading required package: proto
## Loading required package: RSQLite
## Loading required package: DBI
## Loading required package: tcltk
##   LifeExpectancy.cut.fctr  .src  .n
## 1                 (71,83]  Test 107
## 2                 (71,83] Train 107
## 3                 (59,71]  Test  54
## 4                 (59,71] Train  54
## 5                 (47,59]  Test  33
## 6                 (47,59] Train  33
##   LifeExpectancy.cut.fctr  .src  .n
## 1                 (71,83]  Test 107
## 2                 (71,83] Train 107
## 3                 (59,71]  Test  54
## 4                 (59,71] Train  54
## 5                 (47,59]  Test  33
## 6                 (47,59] Train  33
## Loading required package: RColorBrewer

##    .src  .n
## 1  Test 194
## 2 Train 194
## Loading required package: lazyeval
## Loading required package: gdata
## gdata: read.xls support for 'XLS' (Excel 97-2004) files ENABLED.
## 
## gdata: read.xls support for 'XLSX' (Excel 2007+) files ENABLED.
## 
## Attaching package: 'gdata'
## The following objects are masked from 'package:dplyr':
## 
##     combine, first, last
## The following object is masked from 'package:stats':
## 
##     nobs
## The following object is masked from 'package:utils':
## 
##     object.size
## [1] "Skipping duplicates check since glbObsNewFile$splitSpecs$method == 'copy'"
##          label step_major step_minor label_minor   bgn   end elapsed
## 1  import.data          1          0           0 5.756 7.591   1.835
## 2 inspect.data          2          0           0 7.591    NA      NA

Step 2.0: inspect data

## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

## [1] "numeric data missing in glbObsAll: "
##                 FertilityRate           CellularSubscribers 
##                            22                            20 
##                  LiteracyRate                           GNI 
##                           182                            64 
##   PrimarySchoolEnrollmentMale PrimarySchoolEnrollmentFemale 
##                           186                           186 
## [1] "numeric data w/ 0s in glbObsAll: "
## named integer(0)
## [1] "numeric data w/ Infs in glbObsAll: "
## named integer(0)
## [1] "numeric data w/ NaNs in glbObsAll: "
## named integer(0)
## [1] "string data missing in glbObsAll: "
## Country  Region 
##       0       0

## Warning: Removed 22 rows containing non-finite values (stat_smooth).

## Warning: Removed 22 rows containing non-finite values (stat_smooth).
## Warning: Removed 22 rows containing missing values (geom_point).

## Warning: Removed 20 rows containing non-finite values (stat_smooth).
## Warning: Removed 20 rows containing non-finite values (stat_smooth).
## Warning: Removed 20 rows containing missing values (geom_point).

## NULL
##          label step_major step_minor label_minor    bgn    end elapsed
## 2 inspect.data          2          0           0  7.591 14.998   7.407
## 3   scrub.data          2          1           1 14.998     NA      NA

Step 2.1: scrub data

## [1] "numeric data missing in glbObsAll: "
##                 FertilityRate           CellularSubscribers 
##                            22                            20 
##                  LiteracyRate                           GNI 
##                           182                            64 
##   PrimarySchoolEnrollmentMale PrimarySchoolEnrollmentFemale 
##                           186                           186 
## [1] "numeric data w/ 0s in glbObsAll: "
## named integer(0)
## [1] "numeric data w/ Infs in glbObsAll: "
## named integer(0)
## [1] "numeric data w/ NaNs in glbObsAll: "
## named integer(0)
## [1] "string data missing in glbObsAll: "
## Country  Region 
##       0       0
##            label step_major step_minor label_minor    bgn    end elapsed
## 3     scrub.data          2          1           1 14.998 18.144   3.146
## 4 transform.data          2          2           2 18.144     NA      NA

Step 2.2: transform data

##              label step_major step_minor label_minor    bgn    end elapsed
## 4   transform.data          2          2           2 18.144 18.183   0.039
## 5 extract.features          3          0           0 18.183     NA      NA

Step 3.0: extract features

##                       label step_major step_minor label_minor    bgn
## 5          extract.features          3          0           0 18.183
## 6 extract.features.datetime          3          1           1 18.204
##      end elapsed
## 5 18.203    0.02
## 6     NA      NA

Step 3.1: extract features datetime

##                           label step_major step_minor label_minor   bgn
## 1 extract.features.datetime.bgn          1          0           0 18.23
##   end elapsed
## 1  NA      NA
##                       label step_major step_minor label_minor    bgn
## 6 extract.features.datetime          3          1           1 18.204
## 7    extract.features.image          3          2           2 18.239
##      end elapsed
## 6 18.239   0.035
## 7     NA      NA

Step 3.2: extract features image

```{r extract.features.image, cache=FALSE, echo=FALSE, fig.height=5, fig.width=5, eval=myevlChunk(glbChunks, glbOut$pfx)}

##                        label step_major step_minor label_minor    bgn end
## 1 extract.features.image.bgn          1          0           0 18.272  NA
##   elapsed
## 1      NA
##                        label step_major step_minor label_minor    bgn
## 1 extract.features.image.bgn          1          0           0 18.272
## 2 extract.features.image.end          2          0           0 18.281
##     end elapsed
## 1 18.28   0.009
## 2    NA      NA
##                        label step_major step_minor label_minor    bgn
## 1 extract.features.image.bgn          1          0           0 18.272
## 2 extract.features.image.end          2          0           0 18.281
##     end elapsed
## 1 18.28   0.009
## 2    NA      NA
##                    label step_major step_minor label_minor    bgn   end
## 7 extract.features.image          3          2           2 18.239 18.29
## 8 extract.features.price          3          3           3 18.291    NA
##   elapsed
## 7   0.051
## 8      NA

Step 3.3: extract features price

##                        label step_major step_minor label_minor    bgn end
## 1 extract.features.price.bgn          1          0           0 18.317  NA
##   elapsed
## 1      NA
##                    label step_major step_minor label_minor    bgn    end
## 8 extract.features.price          3          3           3 18.291 18.326
## 9  extract.features.text          3          4           4 18.327     NA
##   elapsed
## 8   0.035
## 9      NA

Step 3.4: extract features text

##                       label step_major step_minor label_minor    bgn end
## 1 extract.features.text.bgn          1          0           0 18.367  NA
##   elapsed
## 1      NA
##                      label step_major step_minor label_minor    bgn    end
## 9    extract.features.text          3          4           4 18.327 18.376
## 10 extract.features.string          3          5           5 18.376     NA
##    elapsed
## 9    0.049
## 10      NA

Step 3.5: extract features string

##                         label step_major step_minor label_minor    bgn end
## 1 extract.features.string.bgn          1          0           0 18.424  NA
##   elapsed
## 1      NA
##                                       label step_major step_minor
## 1               extract.features.string.bgn          1          0
## 2 extract.features.stringfactorize.str.vars          2          0
##   label_minor    bgn    end elapsed
## 1           0 18.424 18.434    0.01
## 2           0 18.435     NA      NA
##   Country    Region      .src 
## "Country"  "Region"    ".src"
## Warning: Creating factors of string variable: Country: # of unique values:
## 194
## Warning: Creating factors of string variable: Region: # of unique values: 6
##                      label step_major step_minor label_minor    bgn    end
## 10 extract.features.string          3          5           5 18.376 18.452
## 11    extract.features.end          3          6           6 18.453     NA
##    elapsed
## 10   0.076
## 11      NA

Step 3.6: extract features end

## time trans    "bgn " "fit.data.training.all " "predict.data.new " "end " 
## 0.0000   multiple enabled transitions:  data.training.all data.new model.selected    firing:  data.training.all 
## 1.0000    1   2 1 0 0 
## 1.0000   multiple enabled transitions:  data.training.all data.new model.selected model.final data.training.all.prediction   firing:  data.new 
## 2.0000    2   1 1 1 0

##                   label step_major step_minor label_minor    bgn    end
## 11 extract.features.end          3          6           6 18.453 19.321
## 12  manage.missing.data          4          0           0 19.321     NA
##    elapsed
## 11   0.868
## 12      NA

Step 4.0: manage missing data

## [1] "numeric data missing in glbObsAll: "
##                 FertilityRate           CellularSubscribers 
##                            22                            20 
##                  LiteracyRate                           GNI 
##                           182                            64 
##   PrimarySchoolEnrollmentMale PrimarySchoolEnrollmentFemale 
##                           186                           186 
## [1] "numeric data w/ 0s in glbObsAll: "
## named integer(0)
## [1] "numeric data w/ Infs in glbObsAll: "
## named integer(0)
## [1] "numeric data w/ NaNs in glbObsAll: "
## named integer(0)
## [1] "string data missing in glbObsAll: "
## Country  Region 
##       0       0
## [1] "Missing data for numerics:"
##                 FertilityRate           CellularSubscribers 
##                            22                            20 
##                  LiteracyRate                           GNI 
##                           182                            64 
##   PrimarySchoolEnrollmentMale PrimarySchoolEnrollmentFemale 
##                           186                           186
## Loading required package: mice
## Loading required package: Rcpp
## mice 2.25 2015-11-09
## [1] "Summary before imputation: "
##    Population         Under15          Over60      FertilityRate  
##  Min.   :      1   Min.   :13.12   Min.   : 0.81   Min.   :1.260  
##  1st Qu.:   1664   1st Qu.:18.64   1st Qu.: 5.18   1st Qu.:1.833  
##  Median :   7790   Median :28.65   Median : 8.53   Median :2.400  
##  Mean   :  36360   Mean   :28.73   Mean   :11.16   Mean   :2.941  
##  3rd Qu.:  24763   3rd Qu.:37.88   3rd Qu.:16.72   3rd Qu.:3.908  
##  Max.   :1390000   Max.   :49.99   Max.   :31.92   Max.   :7.580  
##                                                    NA's   :22     
##  ChildMortality   CellularSubscribers                Region.fctr 
##  Min.   :  2.20   Min.   :  2.57      Europe               :106  
##  1st Qu.:  8.40   1st Qu.: 63.57      Africa               : 92  
##  Median : 18.60   Median : 97.75      Americas             : 70  
##  Mean   : 36.15   Mean   : 93.64      Eastern Mediterranean: 44  
##  3rd Qu.: 56.30   3rd Qu.:120.81      South-East Asia      : 22  
##  Max.   :181.60   Max.   :196.41      Western Pacific      : 54  
##                   NA's   :20                                     
## 
##  iter imp variable
##   1   1  FertilityRate  CellularSubscribers
##   1   2  FertilityRate  CellularSubscribers
##   1   3  FertilityRate  CellularSubscribers
##   1   4  FertilityRate  CellularSubscribers
##   1   5  FertilityRate  CellularSubscribers
##   2   1  FertilityRate  CellularSubscribers
##   2   2  FertilityRate  CellularSubscribers
##   2   3  FertilityRate  CellularSubscribers
##   2   4  FertilityRate  CellularSubscribers
##   2   5  FertilityRate  CellularSubscribers
##   3   1  FertilityRate  CellularSubscribers
##   3   2  FertilityRate  CellularSubscribers
##   3   3  FertilityRate  CellularSubscribers
##   3   4  FertilityRate  CellularSubscribers
##   3   5  FertilityRate  CellularSubscribers
##   4   1  FertilityRate  CellularSubscribers
##   4   2  FertilityRate  CellularSubscribers
##   4   3  FertilityRate  CellularSubscribers
##   4   4  FertilityRate  CellularSubscribers
##   4   5  FertilityRate  CellularSubscribers
##   5   1  FertilityRate  CellularSubscribers
##   5   2  FertilityRate  CellularSubscribers
##   5   3  FertilityRate  CellularSubscribers
##   5   4  FertilityRate  CellularSubscribers
##   5   5  FertilityRate  CellularSubscribers
##    Population         Under15          Over60      FertilityRate  
##  Min.   :      1   Min.   :13.12   Min.   : 0.81   Min.   :1.260  
##  1st Qu.:   1664   1st Qu.:18.64   1st Qu.: 5.18   1st Qu.:1.837  
##  Median :   7790   Median :28.65   Median : 8.53   Median :2.380  
##  Mean   :  36360   Mean   :28.73   Mean   :11.16   Mean   :2.901  
##  3rd Qu.:  24763   3rd Qu.:37.88   3rd Qu.:16.72   3rd Qu.:3.810  
##  Max.   :1390000   Max.   :49.99   Max.   :31.92   Max.   :7.580  
##  ChildMortality   CellularSubscribers                Region.fctr 
##  Min.   :  2.20   Min.   :  2.57      Europe               :106  
##  1st Qu.:  8.40   1st Qu.: 63.70      Africa               : 92  
##  Median : 18.60   Median : 97.75      Americas             : 70  
##  Mean   : 36.15   Mean   : 94.30      Eastern Mediterranean: 44  
##  3rd Qu.: 56.30   3rd Qu.:122.98      South-East Asia      : 22  
##  Max.   :181.60   Max.   :196.41      Western Pacific      : 54
## [1] "numeric data missing in glbObsAll: "
##                 FertilityRate           CellularSubscribers 
##                            22                            20 
##                  LiteracyRate                           GNI 
##                           182                            64 
##   PrimarySchoolEnrollmentMale PrimarySchoolEnrollmentFemale 
##                           186                           186 
## [1] "numeric data w/ 0s in glbObsAll: "
## named integer(0)
## [1] "numeric data w/ Infs in glbObsAll: "
## named integer(0)
## [1] "numeric data w/ NaNs in glbObsAll: "
## named integer(0)
## [1] "string data missing in glbObsAll: "
## Country  Region 
##       0       0
##                  label step_major step_minor label_minor    bgn    end
## 12 manage.missing.data          4          0           0 19.321 20.206
## 13        cluster.data          5          0           0 20.206     NA
##    elapsed
## 12   0.885
## 13      NA

Step 5.0: cluster data

##                      label step_major step_minor label_minor    bgn    end
## 13            cluster.data          5          0           0 20.206 20.252
## 14 partition.data.training          6          0           0 20.253     NA
##    elapsed
## 13   0.047
## 14      NA

Step 6.0: partition data training

## [1] "partition.data.training chunk: setup: elapsed: 0.00 secs"
## [1] "Newdata contains non-NA data for LifeExpectancy; setting OOB to Newdata"
## [1] "partition.data.training chunk: Fit/OOB partition complete: elapsed: 0.01 secs"
##   .category .n.Fit .n.OOB .n.Tst .freqRatio.Fit .freqRatio.OOB
## 1    .dummy    194    194    194              1              1
##   .freqRatio.Tst
## 1              1
## [1] "glbObsAll: "
## [1] 388  23
## [1] "glbObsTrn: "
## [1] 194  23
## [1] "glbObsFit: "
## [1] 194  22
## [1] "glbObsOOB: "
## [1] 194  22
## [1] "glbObsNew: "
## [1] 194  22
## [1] "partition.data.training chunk: teardown: elapsed: 0.10 secs"
##                      label step_major step_minor label_minor    bgn    end
## 14 partition.data.training          6          0           0 20.253 20.411
## 15         select.features          7          0           0 20.412     NA
##    elapsed
## 14   0.158
## 15      NA

Step 7.0: select features

## Warning in cor(data.matrix(entity_df[, sel_feats]), y =
## as.numeric(entity_df[, : the standard deviation is zero
## Loading required package: reshape2
## [1] "cor(FertilityRate.nonNA, Under15)=0.9329"
## [1] "cor(LifeExpectancy, FertilityRate.nonNA)=-0.8348"
## [1] "cor(LifeExpectancy, Under15)=-0.8365"
## Warning in myfind_cor_features(feats_df = glb_feats_df, obs_df =
## glbObsTrn, : Identified FertilityRate.nonNA as highly correlated with
## Under15
## [1] "cor(Over60, Under15)=-0.8294"
## [1] "cor(LifeExpectancy, Over60)=0.6881"
## [1] "cor(LifeExpectancy, Under15)=-0.8365"
## Warning in myfind_cor_features(feats_df = glb_feats_df, obs_df =
## glbObsTrn, : Identified Over60 as highly correlated with Under15
## [1] "cor(ChildMortality, Under15)=0.8151"
## [1] "cor(LifeExpectancy, ChildMortality)=-0.9246"
## [1] "cor(LifeExpectancy, Under15)=-0.8365"
## Warning in myfind_cor_features(feats_df = glb_feats_df, obs_df =
## glbObsTrn, : Identified Under15 as highly correlated with ChildMortality
##                                      cor.y exclude.as.feat   cor.y.abs
## LiteracyRate                   0.725924354               1 0.725924354
## PrimarySchoolEnrollmentFemale  0.711333918               1 0.711333918
## Over60                         0.688129029               0 0.688129029
## GNI                            0.665785621               1 0.665785621
## PrimarySchoolEnrollmentMale    0.630538168               1 0.630538168
## CellularSubscribers            0.623250842               1 0.623250842
## CellularSubscribers.nonNA      0.610735054               0 0.610735054
## .rnorm                         0.081812822               0 0.081812822
## Population                     0.016277014               0 0.016277014
## Region.fctr                    0.002056609               0 0.002056609
## .pos                          -0.020262123               0 0.020262123
## .pos.y                        -0.020262123               0 0.020262123
## Country.fctr                  -0.026371656               1 0.026371656
## FertilityRate.nonNA           -0.834846352               0 0.834846352
## Under15                       -0.836466728               0 0.836466728
## FertilityRate                 -0.839839511               1 0.839839511
## ChildMortality                -0.924563674               0 0.924563674
## .category                               NA               1          NA
##                                   cor.high.X freqRatio percentUnique
## LiteracyRate                            <NA>  2.000000    40.7216495
## PrimarySchoolEnrollmentFemale           <NA>  1.000000    39.6907216
## Over60                               Under15  1.333333    89.6907216
## GNI                                     <NA>  1.000000    80.9278351
## PrimarySchoolEnrollmentMale             <NA>  1.250000    38.6597938
## CellularSubscribers                     <NA>  1.000000    92.7835052
## CellularSubscribers.nonNA               <NA>  1.500000    92.7835052
## .rnorm                                  <NA>  1.000000   100.0000000
## Population                              <NA>  1.000000    98.4536082
## Region.fctr                             <NA>  1.152174     3.0927835
## .pos                                    <NA>  1.000000   100.0000000
## .pos.y                                  <NA>  1.000000   100.0000000
## Country.fctr                            <NA>  1.000000   100.0000000
## FertilityRate.nonNA                  Under15  1.000000    73.7113402
## Under15                       ChildMortality  1.333333    92.2680412
## FertilityRate                           <NA>  1.250000    73.7113402
## ChildMortality                          <NA>  1.333333    87.6288660
## .category                               <NA>  0.000000     0.5154639
##                               zeroVar   nzv is.cor.y.abs.low
## LiteracyRate                    FALSE FALSE            FALSE
## PrimarySchoolEnrollmentFemale   FALSE FALSE            FALSE
## Over60                          FALSE FALSE            FALSE
## GNI                             FALSE FALSE            FALSE
## PrimarySchoolEnrollmentMale     FALSE FALSE            FALSE
## CellularSubscribers             FALSE FALSE            FALSE
## CellularSubscribers.nonNA       FALSE FALSE            FALSE
## .rnorm                          FALSE FALSE            FALSE
## Population                      FALSE FALSE             TRUE
## Region.fctr                     FALSE FALSE             TRUE
## .pos                            FALSE FALSE             TRUE
## .pos.y                          FALSE FALSE             TRUE
## Country.fctr                    FALSE FALSE             TRUE
## FertilityRate.nonNA             FALSE FALSE            FALSE
## Under15                         FALSE FALSE            FALSE
## FertilityRate                   FALSE FALSE            FALSE
## ChildMortality                  FALSE FALSE            FALSE
## .category                        TRUE  TRUE               NA
## Warning in myplot_scatter(plt_feats_df, "percentUnique", "freqRatio",
## colorcol_name = "nzv", : converting nzv to class:factor
## Warning: Removed 16 rows containing missing values (geom_point).

## Warning: Removed 16 rows containing missing values (geom_point).

## Warning: Removed 16 rows containing missing values (geom_point).

##           cor.y exclude.as.feat cor.y.abs cor.high.X freqRatio
## .category    NA               1        NA       <NA>         0
##           percentUnique zeroVar  nzv is.cor.y.abs.low
## .category     0.5154639    TRUE TRUE               NA

## [1] "numeric data missing in glbObsAll: "
##                 FertilityRate           CellularSubscribers 
##                            22                            20 
##                  LiteracyRate                           GNI 
##                           182                            64 
##   PrimarySchoolEnrollmentMale PrimarySchoolEnrollmentFemale 
##                           186                           186 
## [1] "numeric data w/ 0s in glbObsAll: "
## named integer(0)
## [1] "numeric data w/ Infs in glbObsAll: "
## named integer(0)
## [1] "numeric data w/ NaNs in glbObsAll: "
## named integer(0)
## [1] "string data missing in glbObsAll: "
## Country  Region    .lcn 
##       0       0       0
## [1] "glb_feats_df:"
## [1] 18 12
##                            id exclude.as.feat rsp_var
## LifeExpectancy LifeExpectancy            TRUE    TRUE
##                            id cor.y exclude.as.feat cor.y.abs cor.high.X
## LifeExpectancy LifeExpectancy    NA            TRUE        NA       <NA>
##                freqRatio percentUnique zeroVar nzv is.cor.y.abs.low
## LifeExpectancy        NA            NA      NA  NA               NA
##                interaction.feat shapiro.test.p.value rsp_var_raw id_var
## LifeExpectancy               NA                   NA          NA     NA
##                rsp_var
## LifeExpectancy    TRUE
## [1] "glb_feats_df vs. glbObsAll: "
## character(0)
## [1] "glbObsAll vs. glb_feats_df: "
## character(0)
##              label step_major step_minor label_minor    bgn    end elapsed
## 15 select.features          7          0           0 20.412 21.984   1.572
## 16      fit.models          8          0           0 21.984     NA      NA

Step 8.0: fit models

fit.models_0_chunk_df <- myadd_chunk(NULL, "fit.models_0_bgn", label.minor = "setup")
##              label step_major step_minor label_minor    bgn end elapsed
## 1 fit.models_0_bgn          1          0       setup 22.513  NA      NA
# load(paste0(glbOut$pfx, "dsk.RData"))

get_model_sel_frmla <- function() {
    model_evl_terms <- c(NULL)
    # min.aic.fit might not be avl
    lclMdlEvlCriteria <- 
        glbMdlMetricsEval[glbMdlMetricsEval %in% names(glb_models_df)]
    for (metric in lclMdlEvlCriteria)
        model_evl_terms <- c(model_evl_terms, 
                             ifelse(length(grep("max", metric)) > 0, "-", "+"), metric)
    if (glb_is_classification && glb_is_binomial)
        model_evl_terms <- c(model_evl_terms, "-", "opt.prob.threshold.OOB")
    model_sel_frmla <- as.formula(paste(c("~ ", model_evl_terms), collapse = " "))
    return(model_sel_frmla)
}

get_dsp_models_df <- function() {
    dsp_models_cols <- c("id", 
                    glbMdlMetricsEval[glbMdlMetricsEval %in% names(glb_models_df)],
                    grep("opt.", names(glb_models_df), fixed = TRUE, value = TRUE)) 
    dsp_models_df <- 
        #orderBy(get_model_sel_frmla(), glb_models_df)[, c("id", glbMdlMetricsEval)]
        orderBy(get_model_sel_frmla(), glb_models_df)[, dsp_models_cols]    
    nCvMdl <- sapply(glb_models_lst, function(mdl) nrow(mdl$results))
    nParams <- sapply(glb_models_lst, function(mdl) ifelse(mdl$method == "custom", 0, 
        nrow(subset(modelLookup(mdl$method), parameter != "parameter"))))
    
#     nCvMdl <- nCvMdl[names(nCvMdl) != "avNNet"]
#     nParams <- nParams[names(nParams) != "avNNet"]    
    
    if (length(cvMdlProblems <- nCvMdl[nCvMdl <= nParams]) > 0) {
        print("Cross Validation issues:")
        warning("Cross Validation issues:")        
        print(cvMdlProblems)
    }
    
    pltMdls <- setdiff(names(nCvMdl), names(cvMdlProblems))
    pltMdls <- setdiff(pltMdls, names(nParams[nParams == 0]))
    
    # length(pltMdls) == 21
    png(paste0(glbOut$pfx, "bestTune.png"), width = 480 * 2, height = 480 * 4)
    grid.newpage()
    pushViewport(viewport(layout = grid.layout(ceiling(length(pltMdls) / 2.0), 2)))
    pltIx <- 1
    for (mdlId in pltMdls) {
        print(ggplot(glb_models_lst[[mdlId]], highBestTune = TRUE) + labs(title = mdlId),   
              vp = viewport(layout.pos.row = ceiling(pltIx / 2.0), 
                            layout.pos.col = ((pltIx - 1) %% 2) + 1))  
        pltIx <- pltIx + 1
    }
    dev.off()

    if (all(row.names(dsp_models_df) != dsp_models_df$id))
        row.names(dsp_models_df) <- dsp_models_df$id
    return(dsp_models_df)
}
#get_dsp_models_df()

if (glb_is_classification && glb_is_binomial && 
        (length(unique(glbObsFit[, glb_rsp_var])) < 2))
    stop("glbObsFit$", glb_rsp_var, ": contains less than 2 unique values: ",
         paste0(unique(glbObsFit[, glb_rsp_var]), collapse=", "))

max_cor_y_x_vars <- orderBy(~ -cor.y.abs, 
        subset(glb_feats_df, (exclude.as.feat == 0) & !nzv & !is.cor.y.abs.low & 
                                is.na(cor.high.X)))[1:2, "id"]
max_cor_y_x_vars <- max_cor_y_x_vars[!is.na(max_cor_y_x_vars)]
if (length(max_cor_y_x_vars) < 2)
    max_cor_y_x_vars <- union(max_cor_y_x_vars, ".pos")

if (!is.null(glb_Baseline_mdl_var)) {
    if ((max_cor_y_x_vars[1] != glb_Baseline_mdl_var) & 
        (glb_feats_df[glb_feats_df$id == max_cor_y_x_vars[1], "cor.y.abs"] > 
         glb_feats_df[glb_feats_df$id == glb_Baseline_mdl_var, "cor.y.abs"]))
        stop(max_cor_y_x_vars[1], " has a higher correlation with ", glb_rsp_var, 
             " than the Baseline var: ", glb_Baseline_mdl_var)
}

glb_model_type <- ifelse(glb_is_regression, "regression", "classification")
    
# Model specs
# c("id.prefix", "method", "type",
#   # trainControl params
#   "preProc.method", "cv.n.folds", "cv.n.repeats", "summary.fn",
#   # train params
#   "metric", "metric.maximize", "tune.df")

# Baseline
if (!is.null(glb_Baseline_mdl_var)) {
    fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
                            paste0("fit.models_0_", "Baseline"), major.inc = FALSE,
                                    label.minor = "mybaseln_classfr")
    ret_lst <- myfit_mdl(mdl_id="Baseline", 
                         model_method="mybaseln_classfr",
                        indepVar=glb_Baseline_mdl_var,
                        rsp_var=glb_rsp_var,
                        fit_df=glbObsFit, OOB_df=glbObsOOB)
}    

# Most Frequent Outcome "MFO" model: mean(y) for regression
#   Not using caret's nullModel since model stats not avl
#   Cannot use rpart for multinomial classification since it predicts non-MFO
if (glb_is_classification) {
    fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
                                paste0("fit.models_0_", "MFO"), major.inc = FALSE,
                                        label.minor = "myMFO_classfr")

    ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
        id.prefix = "MFO", type = glb_model_type, trainControl.method = "none",
        train.method = ifelse(glb_is_regression, "lm", "myMFO_classfr"))),
                            indepVar = ".rnorm", rsp_var = glb_rsp_var,
                            fit_df = glbObsFit, OOB_df = glbObsOOB)

        # "random" model - only for classification; 
        #   none needed for regression since it is same as MFO
    fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
                                paste0("fit.models_0_", "Random"), major.inc = FALSE,
                                        label.minor = "myrandom_classfr")

#stop(here"); glb2Sav(); all.equal(glb_models_df, sav_models_df)    
    ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
        id.prefix = "Random", type = glb_model_type, trainControl.method = "none",
        train.method = "myrandom_classfr")),
                        indepVar = ".rnorm", rsp_var = glb_rsp_var,
                        fit_df = glbObsFit, OOB_df = glbObsOOB)
}

# Max.cor.Y
#   Check impact of cv
#       rpart is not a good candidate since caret does not optimize cp (only tuning parameter of rpart) well
fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
                        paste0("fit.models_0_", "Max.cor.Y.rcv.*X*"), major.inc = FALSE,
                                    label.minor = "glmnet")
##                            label step_major step_minor label_minor    bgn
## 1               fit.models_0_bgn          1          0       setup 22.513
## 2 fit.models_0_Max.cor.Y.rcv.*X*          1          1      glmnet 22.549
##      end elapsed
## 1 22.549   0.036
## 2     NA      NA
ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
    id.prefix = "Max.cor.Y.rcv.1X1", type = glb_model_type, trainControl.method = "none",
    train.method = "glmnet")),
                    indepVar = max_cor_y_x_vars, rsp_var = glb_rsp_var, 
                    fit_df = glbObsFit, OOB_df = glbObsOOB)
## [1] "myfit_mdl: enter: 0.000000 secs"
## [1] "fitting model: Max.cor.Y.rcv.1X1###glmnet"
## [1] "    indepVar: ChildMortality,CellularSubscribers.nonNA"
## [1] "myfit_mdl: setup complete: 1.032000 secs"
## Loading required package: glmnet
## Loading required package: Matrix
## Loaded glmnet 2.0-5
## Fitting alpha = 0.1, lambda = 0.171 on full training set
## [1] "myfit_mdl: train complete: 1.800000 secs"

##             Length Class      Mode     
## a0           80    -none-     numeric  
## beta        160    dgCMatrix  S4       
## df           80    -none-     numeric  
## dim           2    -none-     numeric  
## lambda       80    -none-     numeric  
## dev.ratio    80    -none-     numeric  
## nulldev       1    -none-     numeric  
## npasses       1    -none-     numeric  
## jerr          1    -none-     numeric  
## offset        1    -none-     logical  
## call          5    -none-     call     
## nobs          1    -none-     numeric  
## lambdaOpt     1    -none-     numeric  
## xNames        2    -none-     character
## problemType   1    -none-     character
## tuneValue     2    data.frame list     
## obsLevels     1    -none-     logical  
## [1] "min lambda > lambdaOpt:"
##               (Intercept) CellularSubscribers.nonNA 
##               76.14190451                0.01563283 
##            ChildMortality 
##               -0.21034732 
## [1] "max lambda < lambdaOpt:"
##               (Intercept) CellularSubscribers.nonNA 
##               76.18267877                0.01540236 
##            ChildMortality 
##               -0.21087483 
## [1] "myfit_mdl: train diagnostics complete: 1.890000 secs"
## [1] "myfit_mdl: predict complete: 2.033000 secs"
##                           id                                    feats
## 1 Max.cor.Y.rcv.1X1###glmnet ChildMortality,CellularSubscribers.nonNA
##   max.nTuningRuns min.elapsedtime.everything min.elapsedtime.final
## 1               0                      0.762                 0.011
##   max.R.sq.fit min.RMSE.fit max.Adj.R.sq.fit max.R.sq.OOB min.RMSE.OOB
## 1    0.8565517     3.497785        0.8550496    0.8573102     3.488525
##   max.Adj.R.sq.OOB
## 1        0.8558161
## [1] "myfit_mdl: exit: 2.038000 secs"
if (glbMdlCheckRcv) {
    # rcv_n_folds == 1 & rcv_n_repeats > 1 crashes
    for (rcv_n_folds in seq(3, glb_rcv_n_folds + 2, 2))
        for (rcv_n_repeats in seq(1, glb_rcv_n_repeats + 2, 2)) {
            
            # Experiment specific code to avoid caret crash
    #         lcl_tune_models_df <- rbind(data.frame()
    #                             ,data.frame(method = "glmnet", parameter = "alpha", 
    #                                         vals = "0.100 0.325 0.550 0.775 1.000")
    #                             ,data.frame(method = "glmnet", parameter = "lambda",
    #                                         vals = "9.342e-02")    
    #                                     )
            
            ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst =
                list(
                id.prefix = paste0("Max.cor.Y.rcv.", rcv_n_folds, "X", rcv_n_repeats), 
                type = glb_model_type, 
    # tune.df = lcl_tune_models_df,            
                trainControl.method = "repeatedcv",
                trainControl.number = rcv_n_folds, 
                trainControl.repeats = rcv_n_repeats,
                trainControl.classProbs = glb_is_classification,
                trainControl.summaryFunction = glbMdlMetricSummaryFn,
                train.method = "glmnet", train.metric = glbMdlMetricSummary, 
                train.maximize = glbMdlMetricMaximize)),
                                indepVar = max_cor_y_x_vars, rsp_var = glb_rsp_var, 
                                fit_df = glbObsFit, OOB_df = glbObsOOB)
        }
    # Add parallel coordinates graph of glb_models_df[, glbMdlMetricsEval] to evaluate cv parameters
    tmp_models_cols <- c("id", "max.nTuningRuns",
                        glbMdlMetricsEval[glbMdlMetricsEval %in% names(glb_models_df)],
                        grep("opt.", names(glb_models_df), fixed = TRUE, value = TRUE)) 
    print(myplot_parcoord(obs_df = subset(glb_models_df, 
                                          grepl("Max.cor.Y.rcv.", id, fixed = TRUE), 
                                            select = -feats)[, tmp_models_cols],
                          id_var = "id"))
}
        
# Useful for stacking decisions
# fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
#                     paste0("fit.models_0_", "Max.cor.Y[rcv.1X1.cp.0|]"), major.inc = FALSE,
#                                     label.minor = "rpart")
# 
# ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
#     id.prefix = "Max.cor.Y.rcv.1X1.cp.0", type = glb_model_type, trainControl.method = "none",
#     train.method = "rpart",
#     tune.df=data.frame(method="rpart", parameter="cp", min=0.0, max=0.0, by=0.1))),
#                     indepVar=max_cor_y_x_vars, rsp_var=glb_rsp_var, 
#                     fit_df=glbObsFit, OOB_df=glbObsOOB)

#stop(here"); glb2Sav(); all.equal(glb_models_df, sav_models_df)
# if (glb_is_regression || glb_is_binomial) # For multinomials this model will be run next by default
ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
                        id.prefix = "Max.cor.Y", 
                        type = glb_model_type, trainControl.method = "repeatedcv",
                        trainControl.number = glb_rcv_n_folds, 
                        trainControl.repeats = glb_rcv_n_repeats,
                        trainControl.classProbs = glb_is_classification,
                        trainControl.summaryFunction = glbMdlMetricSummaryFn,
                        trainControl.allowParallel = glbMdlAllowParallel,                        
                        train.metric = glbMdlMetricSummary, 
                        train.maximize = glbMdlMetricMaximize,    
                        train.method = "rpart")),
                    indepVar = max_cor_y_x_vars, rsp_var = glb_rsp_var, 
                    fit_df = glbObsFit, OOB_df = glbObsOOB)
## [1] "myfit_mdl: enter: 0.000000 secs"
## [1] "fitting model: Max.cor.Y##rcv#rpart"
## [1] "    indepVar: ChildMortality,CellularSubscribers.nonNA"
## [1] "myfit_mdl: setup complete: 0.721000 secs"
## Loading required package: rpart
## Warning in nominalTrainWorkflow(x = x, y = y, wts = weights, info =
## trainInfo, : There were missing values in resampled performance measures.
## Aggregating results
## Selecting tuning parameters
## Fitting cp = 0.0104 on full training set
## [1] "myfit_mdl: train complete: 1.958000 secs"
## Warning in myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst
## = list(id.prefix = "Max.cor.Y", : model's bestTune found at an extreme of
## tuneGrid for parameter: cp
## Loading required package: rpart.plot

## Call:
## rpart(formula = .outcome ~ ., control = list(minsplit = 20, minbucket = 7, 
##     cp = 0, maxcompete = 4, maxsurrogate = 5, usesurrogate = 2, 
##     surrogatestyle = 0, maxdepth = 30, xval = 0))
##   n= 194 
## 
##           CP nsplit rel error
## 1 0.70492837      0 1.0000000
## 2 0.08791502      1 0.2950716
## 3 0.07368671      2 0.2071566
## 4 0.01798421      3 0.1334699
## 5 0.01044633      4 0.1154857
## 
## Variable importance
##            ChildMortality CellularSubscribers.nonNA 
##                        68                        32 
## 
## Node number 1: 194 observations,    complexity param=0.7049284
##   mean=70.01031, MSE=85.28855 
##   left son=2 (66 obs) right son=3 (128 obs)
##   Primary splits:
##       ChildMortality            < 37.5  to the right, improve=0.7049284, (0 missing)
##       CellularSubscribers.nonNA < 72.66 to the left,  improve=0.4692647, (0 missing)
##   Surrogate splits:
##       CellularSubscribers.nonNA < 74.09 to the left,  agree=0.856, adj=0.576, (0 split)
## 
## Node number 2: 66 observations,    complexity param=0.08791502
##   mean=59.21212, MSE=36.43985 
##   left son=4 (25 obs) right son=5 (41 obs)
##   Primary splits:
##       ChildMortality            < 87.2  to the right, improve=0.6048323, (0 missing)
##       CellularSubscribers.nonNA < 64.64 to the left,  improve=0.1155554, (0 missing)
## 
## Node number 3: 128 observations,    complexity param=0.07368671
##   mean=75.57812, MSE=19.35327 
##   left son=6 (80 obs) right son=7 (48 obs)
##   Primary splits:
##       ChildMortality            < 8.2   to the right, improve=0.4921724, (0 missing)
##       CellularSubscribers.nonNA < 69.95 to the left,  improve=0.1042004, (0 missing)
## 
## Node number 4: 25 observations
##   mean=53.2, MSE=10.08 
## 
## Node number 5: 41 observations
##   mean=62.87805, MSE=17.03391 
## 
## Node number 6: 80 observations,    complexity param=0.01798421
##   mean=73.1875, MSE=10.72734 
##   left son=12 (14 obs) right son=13 (66 obs)
##   Primary splits:
##       ChildMortality            < 25.85 to the right, improve=0.3467381, (0 missing)
##       CellularSubscribers.nonNA < 69.95 to the left,  improve=0.1285743, (0 missing)
##   Surrogate splits:
##       CellularSubscribers.nonNA < 51.2  to the left,  agree=0.862, adj=0.214, (0 split)
## 
## Node number 7: 48 observations
##   mean=79.5625, MSE=8.329427 
## 
## Node number 12: 14 observations
##   mean=69, MSE=6.857143 
## 
## Node number 13: 66 observations
##   mean=74.07576, MSE=7.039715 
## 
## n= 194 
## 
## node), split, n, deviance, yval
##       * denotes terminal node
## 
##  1) root 194 16545.9800 70.01031  
##    2) ChildMortality>=37.5 66  2405.0300 59.21212  
##      4) ChildMortality>=87.2 25   252.0000 53.20000 *
##      5) ChildMortality< 87.2 41   698.3902 62.87805 *
##    3) ChildMortality< 37.5 128  2477.2190 75.57812  
##      6) ChildMortality>=8.2 80   858.1875 73.18750  
##       12) ChildMortality>=25.85 14    96.0000 69.00000 *
##       13) ChildMortality< 25.85 66   464.6212 74.07576 *
##      7) ChildMortality< 8.2 48   399.8125 79.56250 *
## [1] "myfit_mdl: train diagnostics complete: 2.645000 secs"
## [1] "myfit_mdl: predict complete: 2.673000 secs"
##                     id                                    feats
## 1 Max.cor.Y##rcv#rpart ChildMortality,CellularSubscribers.nonNA
##   max.nTuningRuns min.elapsedtime.everything min.elapsedtime.final
## 1               5                      1.234                  0.01
##   max.R.sq.fit min.RMSE.fit max.Adj.R.sq.fit max.R.sq.OOB min.RMSE.OOB
## 1    0.8845143     3.612457               NA    0.8845143     3.138409
##   max.Adj.R.sq.OOB max.Rsquared.fit min.RMSESD.fit max.RsquaredSD.fit
## 1               NA        0.8507488      0.5005967         0.04168522
## [1] "myfit_mdl: exit: 2.682000 secs"
if ((length(glbFeatsDateTime) > 0) && 
    (sum(grepl(paste(names(glbFeatsDateTime), "\\.day\\.minutes\\.poly\\.", sep = ""),
               names(glbObsAll))) > 0)) {
    fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
                    paste0("fit.models_0_", "Max.cor.Y.Time.Poly"), major.inc = FALSE,
                                    label.minor = "glmnet")

    indepVars <- c(max_cor_y_x_vars, 
            grep(paste(names(glbFeatsDateTime), "\\.day\\.minutes\\.poly\\.", sep = ""),
                        names(glbObsAll), value = TRUE))
    indepVars <- myadjustInteractionFeats(glb_feats_df, indepVars)
    ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
            id.prefix = "Max.cor.Y.Time.Poly", 
            type = glb_model_type, trainControl.method = "repeatedcv",
            trainControl.number = glb_rcv_n_folds, trainControl.repeats = glb_rcv_n_repeats,
            trainControl.classProbs = glb_is_classification,
            trainControl.summaryFunction = glbMdlMetricSummaryFn,
            train.metric = glbMdlMetricSummary, 
            train.maximize = glbMdlMetricMaximize,    
            train.method = "glmnet")),
        indepVar = indepVars,
        rsp_var = glb_rsp_var, 
        fit_df = glbObsFit, OOB_df = glbObsOOB)
}

if ((length(glbFeatsDateTime) > 0) && 
    (sum(grepl(paste(names(glbFeatsDateTime), "\\.last[[:digit:]]", sep = ""),
               names(glbObsAll))) > 0)) {
    fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
                    paste0("fit.models_0_", "Max.cor.Y.Time.Lag"), major.inc = FALSE,
                                    label.minor = "glmnet")

    indepVars <- c(max_cor_y_x_vars, 
            grep(paste(names(glbFeatsDateTime), "\\.last[[:digit:]]", sep = ""),
                        names(glbObsAll), value = TRUE))
    indepVars <- myadjustInteractionFeats(glb_feats_df, indepVars)
    ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
        id.prefix = "Max.cor.Y.Time.Lag", 
        type = glb_model_type, 
        tune.df = glbMdlTuneParams,        
        trainControl.method = "repeatedcv",
        trainControl.number = glb_rcv_n_folds, trainControl.repeats = glb_rcv_n_repeats,
        trainControl.classProbs = glb_is_classification,
        trainControl.summaryFunction = glbMdlMetricSummaryFn,
        train.metric = glbMdlMetricSummary, 
        train.maximize = glbMdlMetricMaximize,    
        train.method = "glmnet")),
        indepVar = indepVars,
        rsp_var = glb_rsp_var, 
        fit_df = glbObsFit, OOB_df = glbObsOOB)
}

if (length(glbFeatsText) > 0) {
    fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
                    paste0("fit.models_0_", "Txt.*"), major.inc = FALSE,
                                    label.minor = "glmnet")

    indepVars <- c(max_cor_y_x_vars)
    for (txtFeat in names(glbFeatsText))
        indepVars <- union(indepVars, 
            grep(paste(str_to_upper(substr(txtFeat, 1, 1)), "\\.(?!([T|P]\\.))", sep = ""),
                        names(glbObsAll), perl = TRUE, value = TRUE))
    indepVars <- myadjustInteractionFeats(glb_feats_df, indepVars)
    ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
        id.prefix = "Max.cor.Y.Text.nonTP", 
        type = glb_model_type, 
        tune.df = glbMdlTuneParams,        
        trainControl.method = "repeatedcv",
        trainControl.number = glb_rcv_n_folds, trainControl.repeats = glb_rcv_n_repeats,
        trainControl.classProbs = glb_is_classification,
        trainControl.summaryFunction = glbMdlMetricSummaryFn,
        trainControl.allowParallel = glbMdlAllowParallel,                                
        train.metric = glbMdlMetricSummary, 
        train.maximize = glbMdlMetricMaximize,    
        train.method = "glmnet")),
        indepVar = indepVars,
        rsp_var = glb_rsp_var, 
        fit_df = glbObsFit, OOB_df = glbObsOOB)

    indepVars <- c(max_cor_y_x_vars)
    for (txtFeat in names(glbFeatsText))
        indepVars <- union(indepVars, 
            grep(paste(str_to_upper(substr(txtFeat, 1, 1)), "\\.T\\.", sep = ""),
                        names(glbObsAll), perl = TRUE, value = TRUE))
    indepVars <- myadjustInteractionFeats(glb_feats_df, indepVars)
    ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
        id.prefix = "Max.cor.Y.Text.onlyT", 
        type = glb_model_type, 
        tune.df = glbMdlTuneParams,        
        trainControl.method = "repeatedcv",
        trainControl.number = glb_rcv_n_folds, trainControl.repeats = glb_rcv_n_repeats,
        trainControl.classProbs = glb_is_classification,
        trainControl.summaryFunction = glbMdlMetricSummaryFn,
        train.metric = glbMdlMetricSummary, 
        train.maximize = glbMdlMetricMaximize,    
        train.method = "glmnet")),
        indepVar = indepVars,
        rsp_var = glb_rsp_var, 
        fit_df = glbObsFit, OOB_df = glbObsOOB)

    indepVars <- c(max_cor_y_x_vars)
    for (txtFeat in names(glbFeatsText))
        indepVars <- union(indepVars, 
            grep(paste(str_to_upper(substr(txtFeat, 1, 1)), "\\.P\\.", sep = ""),
                        names(glbObsAll), perl = TRUE, value = TRUE))
    indepVars <- myadjustInteractionFeats(glb_feats_df, indepVars)
    ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
        id.prefix = "Max.cor.Y.Text.onlyP", 
        type = glb_model_type, 
        tune.df = glbMdlTuneParams,        
        trainControl.method = "repeatedcv",
        trainControl.number = glb_rcv_n_folds, trainControl.repeats = glb_rcv_n_repeats,
        trainControl.classProbs = glb_is_classification,
        trainControl.summaryFunction = glbMdlMetricSummaryFn,
        trainControl.allowParallel = glbMdlAllowParallel,        
        train.metric = glbMdlMetricSummary, 
        train.maximize = glbMdlMetricMaximize,    
        train.method = "glmnet")),
        indepVar = indepVars,
        rsp_var = glb_rsp_var, 
        fit_df = glbObsFit, OOB_df = glbObsOOB)
}

# Interactions.High.cor.Y
if (length(int_feats <- setdiff(setdiff(unique(glb_feats_df$cor.high.X), NA), 
                                subset(glb_feats_df, nzv)$id)) > 0) {
    fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
                    paste0("fit.models_0_", "Interact.High.cor.Y"), major.inc = FALSE,
                                    label.minor = "glmnet")

    ret_lst <- myfit_mdl(mdl_specs_lst=myinit_mdl_specs_lst(mdl_specs_lst=list(
        id.prefix="Interact.High.cor.Y", 
        type=glb_model_type, trainControl.method="repeatedcv",
        trainControl.number=glb_rcv_n_folds, trainControl.repeats=glb_rcv_n_repeats,
        trainControl.classProbs = glb_is_classification,
        trainControl.summaryFunction = glbMdlMetricSummaryFn,
        trainControl.allowParallel = glbMdlAllowParallel,
        train.metric = glbMdlMetricSummary, 
        train.maximize = glbMdlMetricMaximize,    
        train.method="glmnet")),
        indepVar=c(max_cor_y_x_vars, paste(max_cor_y_x_vars[1], int_feats, sep=":")),
        rsp_var=glb_rsp_var, 
        fit_df=glbObsFit, OOB_df=glbObsOOB)
}    
##                              label step_major step_minor label_minor
## 2   fit.models_0_Max.cor.Y.rcv.*X*          1          1      glmnet
## 3 fit.models_0_Interact.High.cor.Y          1          2      glmnet
##      bgn    end elapsed
## 2 22.549 27.394   4.845
## 3 27.395     NA      NA
## [1] "myfit_mdl: enter: 0.000000 secs"
## [1] "fitting model: Interact.High.cor.Y##rcv#glmnet"
## [1] "    indepVar: ChildMortality,CellularSubscribers.nonNA,ChildMortality:Under15,ChildMortality:ChildMortality"
## [1] "myfit_mdl: setup complete: 0.679000 secs"
## Aggregating results
## Selecting tuning parameters
## Fitting alpha = 0.1, lambda = 0.00793 on full training set
## [1] "myfit_mdl: train complete: 2.244000 secs"
## Warning in myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst
## = list(id.prefix = "Interact.High.cor.Y", : model's bestTune found at an
## extreme of tuneGrid for parameter: alpha
## Warning in myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst
## = list(id.prefix = "Interact.High.cor.Y", : model's bestTune found at an
## extreme of tuneGrid for parameter: lambda

##             Length Class      Mode     
## a0          100    -none-     numeric  
## beta        300    dgCMatrix  S4       
## df          100    -none-     numeric  
## dim           2    -none-     numeric  
## lambda      100    -none-     numeric  
## dev.ratio   100    -none-     numeric  
## nulldev       1    -none-     numeric  
## npasses       1    -none-     numeric  
## jerr          1    -none-     numeric  
## offset        1    -none-     logical  
## call          5    -none-     call     
## nobs          1    -none-     numeric  
## lambdaOpt     1    -none-     numeric  
## xNames        3    -none-     character
## problemType   1    -none-     character
## tuneValue     2    data.frame list     
## obsLevels     1    -none-     logical  
## [1] "min lambda > lambdaOpt:"
##               (Intercept) CellularSubscribers.nonNA 
##              77.421467560               0.012002399 
##            ChildMortality    ChildMortality:Under15 
##              -0.335269381               0.002624827 
## [1] "max lambda < lambdaOpt:"
## [1] "Feats mismatch between coefs_left & rght:"
## [1] "(Intercept)"               "CellularSubscribers.nonNA"
## [3] "ChildMortality"            "ChildMortality:Under15"   
## [1] "myfit_mdl: train diagnostics complete: 2.870000 secs"
## [1] "myfit_mdl: predict complete: 2.975000 secs"
##                                id
## 1 Interact.High.cor.Y##rcv#glmnet
##                                                                                           feats
## 1 ChildMortality,CellularSubscribers.nonNA,ChildMortality:Under15,ChildMortality:ChildMortality
##   max.nTuningRuns min.elapsedtime.everything min.elapsedtime.final
## 1              25                      1.561                 0.005
##   max.R.sq.fit min.RMSE.fit max.Adj.R.sq.fit max.R.sq.OOB min.RMSE.OOB
## 1     0.863628     3.508182        0.8614748    0.8641454     3.403945
##   max.Adj.R.sq.OOB max.Rsquared.fit min.RMSESD.fit max.RsquaredSD.fit
## 1        0.8620004        0.8648804      0.3711338         0.02530595
## [1] "myfit_mdl: exit: 2.984000 secs"
# Low.cor.X
fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
                        paste0("fit.models_0_", "Low.cor.X"), major.inc = FALSE,
                                     label.minor = "glmnet")
##                              label step_major step_minor label_minor
## 3 fit.models_0_Interact.High.cor.Y          1          2      glmnet
## 4           fit.models_0_Low.cor.X          1          3      glmnet
##      bgn    end elapsed
## 3 27.395 30.388   2.993
## 4 30.388     NA      NA
indepVar <- mygetIndepVar(glb_feats_df)
ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
            id.prefix = "Low.cor.X", 
            type = glb_model_type, 
            tune.df = glbMdlTuneParams,        
            trainControl.method = "repeatedcv",
            trainControl.number = glb_rcv_n_folds, trainControl.repeats = glb_rcv_n_repeats,
            trainControl.classProbs = glb_is_classification,
            trainControl.summaryFunction = glbMdlMetricSummaryFn,
            trainControl.allowParallel = glbMdlAllowParallel,
            train.metric = glbMdlMetricSummary, 
            train.maximize = glbMdlMetricMaximize,    
            train.method = "glmnet")),
        indepVar = indepVar, rsp_var = glb_rsp_var, 
        fit_df = glbObsFit, OOB_df = glbObsOOB)
## [1] "myfit_mdl: enter: 0.000000 secs"
## [1] "fitting model: Low.cor.X##rcv#glmnet"
## [1] "    indepVar: Over60,CellularSubscribers.nonNA,.rnorm,Population,Region.fctr,.pos,.pos.y,FertilityRate.nonNA,Under15,ChildMortality"
## [1] "myfit_mdl: setup complete: 0.699000 secs"
## Aggregating results
## Selecting tuning parameters
## Fitting alpha = 0.325, lambda = 0.0368 on full training set
## [1] "myfit_mdl: train complete: 2.271000 secs"

##             Length Class      Mode     
## a0            84   -none-     numeric  
## beta        1176   dgCMatrix  S4       
## df            84   -none-     numeric  
## dim            2   -none-     numeric  
## lambda        84   -none-     numeric  
## dev.ratio     84   -none-     numeric  
## nulldev        1   -none-     numeric  
## npasses        1   -none-     numeric  
## jerr           1   -none-     numeric  
## offset         1   -none-     logical  
## call           5   -none-     call     
## nobs           1   -none-     numeric  
## lambdaOpt      1   -none-     numeric  
## xNames        14   -none-     character
## problemType    1   -none-     character
## tuneValue      2   data.frame list     
## obsLevels      1   -none-     logical  
## [1] "min lambda > lambdaOpt:"
##                      (Intercept)                             .pos 
##                     76.694860465                     -0.003728450 
##                           .pos.y                           .rnorm 
##                     -0.003378871                      0.075193372 
##        CellularSubscribers.nonNA                   ChildMortality 
##                      0.006853132                     -0.168446647 
##              FertilityRate.nonNA                           Over60 
##                      1.339044581                      0.185942891 
##                Region.fctrAfrica              Region.fctrAmericas 
##                     -1.777056431                      2.148315203 
## Region.fctrEastern Mediterranean       Region.fctrSouth-East Asia 
##                      1.868369727                      0.709017555 
##       Region.fctrWestern Pacific                          Under15 
##                      1.469834756                     -0.241038585 
## [1] "max lambda < lambdaOpt:"
##                      (Intercept)                             .pos 
##                     7.672078e+01                    -3.745903e-03 
##                           .pos.y                           .rnorm 
##                    -3.390183e-03                     7.483258e-02 
##        CellularSubscribers.nonNA                   ChildMortality 
##                     6.838089e-03                    -1.688486e-01 
##              FertilityRate.nonNA                           Over60 
##                     1.373235e+00                     1.855136e-01 
##                       Population                Region.fctrAfrica 
##                    -6.290707e-09                    -1.763052e+00 
##              Region.fctrAmericas Region.fctrEastern Mediterranean 
##                     2.172714e+00                     1.882474e+00 
##       Region.fctrSouth-East Asia       Region.fctrWestern Pacific 
##                     7.393625e-01                     1.490571e+00 
##                          Under15 
##                    -2.450473e-01 
## [1] "myfit_mdl: train diagnostics complete: 2.847000 secs"
## [1] "myfit_mdl: predict complete: 2.956000 secs"
##                      id
## 1 Low.cor.X##rcv#glmnet
##                                                                                                                   feats
## 1 Over60,CellularSubscribers.nonNA,.rnorm,Population,Region.fctr,.pos,.pos.y,FertilityRate.nonNA,Under15,ChildMortality
##   max.nTuningRuns min.elapsedtime.everything min.elapsedtime.final
## 1              25                      1.566                 0.007
##   max.R.sq.fit min.RMSE.fit max.Adj.R.sq.fit max.R.sq.OOB min.RMSE.OOB
## 1    0.8998973     3.175766         0.892068     0.878346     3.221132
##   max.Adj.R.sq.OOB max.Rsquared.fit min.RMSESD.fit max.RsquaredSD.fit
## 1        0.8688312         0.889112      0.3435573         0.02328833
## [1] "myfit_mdl: exit: 2.964000 secs"
fit.models_0_chunk_df <- 
    myadd_chunk(fit.models_0_chunk_df, "fit.models_0_end", major.inc = FALSE,
                label.minor = "teardown")
##                    label step_major step_minor label_minor    bgn    end
## 4 fit.models_0_Low.cor.X          1          3      glmnet 30.388 33.366
## 5       fit.models_0_end          1          4    teardown 33.367     NA
##   elapsed
## 4   2.978
## 5      NA
rm(ret_lst)

glb_chunks_df <- myadd_chunk(glb_chunks_df, "fit.models", major.inc = FALSE)
##         label step_major step_minor label_minor    bgn    end elapsed
## 16 fit.models          8          0           0 21.984 33.376  11.392
## 17 fit.models          8          1           1 33.377     NA      NA
fit.models_1_chunk_df <- myadd_chunk(NULL, "fit.models_1_bgn", label.minor = "setup")
##              label step_major step_minor label_minor    bgn end elapsed
## 1 fit.models_1_bgn          1          0       setup 34.456  NA      NA
# refactor code for outliers / ensure all model runs exclude outliers in this chunk ???

#stop(here"); glb2Sav(); all.equal(glb_models_df, sav_models_df)
topindep_var <- NULL; interact_vars <- NULL;
for (mdl_id_pfx in names(glbMdlFamilies)) {
    fit.models_1_chunk_df <- 
        myadd_chunk(fit.models_1_chunk_df, paste0("fit.models_1_", mdl_id_pfx),
                    major.inc = FALSE, label.minor = "setup")

    indepVar <- NULL;

    if (grepl("\\.Interact", mdl_id_pfx)) {
        if (is.null(topindep_var) && is.null(interact_vars)) {
        #   select best glmnet model upto now
            dsp_models_df <- orderBy(model_sel_frmla <- get_model_sel_frmla(),
                                     glb_models_df)
            dsp_models_df <- subset(dsp_models_df, 
                                    grepl(".glmnet", id, fixed = TRUE))
            bst_mdl_id <- dsp_models_df$id[1]
            mdl_id_pfx <- 
                paste(c(head(unlist(strsplit(bst_mdl_id, "[.]")), -1), "Interact"),
                      collapse=".")
        #   select important features
            if (is.null(bst_featsimp_df <- 
                        myget_feats_importance(glb_models_lst[[bst_mdl_id]]))) {
                warning("Base model for RFE.Interact: ", bst_mdl_id, 
                        " has no important features")
                next
            }    
            
            topindep_ix <- 1
            while (is.null(topindep_var) && (topindep_ix <= nrow(bst_featsimp_df))) {
                topindep_var <- row.names(bst_featsimp_df)[topindep_ix]
                if (grepl(".fctr", topindep_var, fixed=TRUE))
                    topindep_var <- 
                        paste0(unlist(strsplit(topindep_var, ".fctr"))[1], ".fctr")
                if (topindep_var %in% names(glbFeatsInteractionOnly)) {
                    topindep_var <- NULL; topindep_ix <- topindep_ix + 1
                } else break
            }
            
        #   select features with importance > max(10, importance of .rnorm) & is not highest
        #       combine factor dummy features to just the factor feature
            if (length(pos_rnorm <- 
                       grep(".rnorm", row.names(bst_featsimp_df), fixed=TRUE)) > 0)
                imp_rnorm <- bst_featsimp_df[pos_rnorm, 1] else
                imp_rnorm <- NA    
            imp_cutoff <- max(10, imp_rnorm, na.rm=TRUE)
            interact_vars <- 
                tail(row.names(subset(bst_featsimp_df, 
                                      imp > imp_cutoff)), -1)
            if (length(interact_vars) > 0) {
                interact_vars <-
                    myadjustInteractionFeats(glb_feats_df, myextract_actual_feats(interact_vars))
                interact_vars <- 
                    interact_vars[!grepl(topindep_var, interact_vars, fixed=TRUE)]
            }
            ### bid0_sp only
#             interact_vars <- c(
#     "biddable", "D.ratio.sum.TfIdf.wrds.n", "D.TfIdf.sum.stem.stop.Ratio", "D.sum.TfIdf",
#     "D.TfIdf.sum.post.stop", "D.TfIdf.sum.post.stem", "D.ratio.wrds.stop.n.wrds.n", "D.chrs.uppr.n.log",
#     "D.chrs.n.log", "color.fctr"
#     # , "condition.fctr", "prdl.my.descr.fctr"
#                                 )
#            interact_vars <- setdiff(interact_vars, c("startprice.dgt2.is9", "color.fctr"))
            ###
            indepVar <- myextract_actual_feats(row.names(bst_featsimp_df))
            indepVar <- setdiff(indepVar, topindep_var)
            if (length(interact_vars) > 0) {
                indepVar <- 
                    setdiff(indepVar, myextract_actual_feats(interact_vars))
                indepVar <- c(indepVar, 
                    paste(topindep_var, setdiff(interact_vars, topindep_var), 
                          sep = "*"))
            } else indepVar <- union(indepVar, topindep_var)
        }
    }
    
    if (is.null(indepVar))
        indepVar <- glb_mdl_feats_lst[[mdl_id_pfx]]

    if (is.null(indepVar) && grepl("RFE\\.", mdl_id_pfx))
        indepVar <- myextract_actual_feats(predictors(rfe_fit_results))
    
    if (is.null(indepVar))
        indepVar <- mygetIndepVar(glb_feats_df)
    
    if ((length(indepVar) == 1) && (grepl("^%<d-%", indepVar))) {    
        indepVar <- 
            eval(parse(text = str_trim(unlist(strsplit(indepVar, "%<d-%"))[2])))
    }    

    indepVar <- myadjustInteractionFeats(glb_feats_df, indepVar)
    
    if (grepl("\\.Interact", mdl_id_pfx)) { 
        # if (method != tail(unlist(strsplit(bst_mdl_id, "[.]")), 1)) next
        if (is.null(glbMdlFamilies[[mdl_id_pfx]])) {
            if (!is.null(glbMdlFamilies[["Best.Interact"]]))
                glbMdlFamilies[[mdl_id_pfx]] <-
                    glbMdlFamilies[["Best.Interact"]]
        }
    }
    
    if (!is.null(glbObsFitOutliers[[mdl_id_pfx]])) {
        fitobs_df <- glbObsFit[!(glbObsFit[, glbFeatsId] %in%
                                         glbObsFitOutliers[[mdl_id_pfx]]), ]
        print(sprintf("Outliers removed: %d", nrow(glbObsFit) - nrow(fitobs_df)))
        print(setdiff(glbObsFit[, glbFeatsId], fitobs_df[, glbFeatsId]))
    } else fitobs_df <- glbObsFit

    if (is.null(glbMdlFamilies[[mdl_id_pfx]]))
        mdl_methods <- glbMdlMethods else
        mdl_methods <- glbMdlFamilies[[mdl_id_pfx]]    

    for (method in mdl_methods) {
        if (method %in% c("rpart", "rf")) {
            # rpart:    fubar's the tree
            # rf:       skip the scenario w/ .rnorm for speed
            indepVar <- setdiff(indepVar, c(".rnorm"))
            #mdl_id <- paste0(mdl_id_pfx, ".no.rnorm")
        } 

        fit.models_1_chunk_df <- myadd_chunk(fit.models_1_chunk_df, 
                            paste0("fit.models_1_", mdl_id_pfx), major.inc = FALSE,
                                    label.minor = method)

        ret_lst <- 
            myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
            id.prefix = mdl_id_pfx, 
            type = glb_model_type, 
            tune.df = glbMdlTuneParams,
            trainControl.method = "repeatedcv", # or "none" if nominalWorkflow is crashing
            trainControl.number = glb_rcv_n_folds,
            trainControl.repeats = glb_rcv_n_repeats,
            trainControl.classProbs = glb_is_classification,
            trainControl.summaryFunction = glbMdlMetricSummaryFn,
            trainControl.allowParallel = glbMdlAllowParallel,            
            train.metric = glbMdlMetricSummary, 
            train.maximize = glbMdlMetricMaximize,    
            train.method = method)),
            indepVar = indepVar, rsp_var = glb_rsp_var, 
            fit_df = fitobs_df, OOB_df = glbObsOOB)
        
#         ntv_mdl <- glmnet(x = as.matrix(
#                               fitobs_df[, indepVar]), 
#                           y = as.factor(as.character(
#                               fitobs_df[, glb_rsp_var])),
#                           family = "multinomial")
#         bgn = 1; end = 100;
#         ntv_mdl <- glmnet(x = as.matrix(
#                               subset(fitobs_df, pop.fctr != "crypto")[bgn:end, indepVar]), 
#                           y = as.factor(as.character(
#                               subset(fitobs_df, pop.fctr != "crypto")[bgn:end, glb_rsp_var])),
#                           family = "multinomial")
    }
}
##                label step_major step_minor label_minor    bgn    end
## 1   fit.models_1_bgn          1          0       setup 34.456 34.466
## 2 fit.models_1_All.X          1          1       setup 34.467     NA
##   elapsed
## 1    0.01
## 2      NA
##                label step_major step_minor label_minor    bgn    end
## 2 fit.models_1_All.X          1          1       setup 34.467 34.473
## 3 fit.models_1_All.X          1          2      glmnet 34.474     NA
##   elapsed
## 2   0.007
## 3      NA
## [1] "myfit_mdl: enter: 0.000000 secs"
## [1] "fitting model: All.X##rcv#glmnet"
## [1] "    indepVar: Over60,CellularSubscribers.nonNA,.rnorm,Population,Region.fctr,.pos,.pos.y,FertilityRate.nonNA,Under15,ChildMortality"
## [1] "myfit_mdl: setup complete: 0.692000 secs"
## Aggregating results
## Selecting tuning parameters
## Fitting alpha = 0.325, lambda = 0.0368 on full training set
## [1] "myfit_mdl: train complete: 2.287000 secs"

##             Length Class      Mode     
## a0            84   -none-     numeric  
## beta        1176   dgCMatrix  S4       
## df            84   -none-     numeric  
## dim            2   -none-     numeric  
## lambda        84   -none-     numeric  
## dev.ratio     84   -none-     numeric  
## nulldev        1   -none-     numeric  
## npasses        1   -none-     numeric  
## jerr           1   -none-     numeric  
## offset         1   -none-     logical  
## call           5   -none-     call     
## nobs           1   -none-     numeric  
## lambdaOpt      1   -none-     numeric  
## xNames        14   -none-     character
## problemType    1   -none-     character
## tuneValue      2   data.frame list     
## obsLevels      1   -none-     logical  
## [1] "min lambda > lambdaOpt:"
##                      (Intercept)                             .pos 
##                     76.694860465                     -0.003728450 
##                           .pos.y                           .rnorm 
##                     -0.003378871                      0.075193372 
##        CellularSubscribers.nonNA                   ChildMortality 
##                      0.006853132                     -0.168446647 
##              FertilityRate.nonNA                           Over60 
##                      1.339044581                      0.185942891 
##                Region.fctrAfrica              Region.fctrAmericas 
##                     -1.777056431                      2.148315203 
## Region.fctrEastern Mediterranean       Region.fctrSouth-East Asia 
##                      1.868369727                      0.709017555 
##       Region.fctrWestern Pacific                          Under15 
##                      1.469834756                     -0.241038585 
## [1] "max lambda < lambdaOpt:"
##                      (Intercept)                             .pos 
##                     7.672078e+01                    -3.745903e-03 
##                           .pos.y                           .rnorm 
##                    -3.390183e-03                     7.483258e-02 
##        CellularSubscribers.nonNA                   ChildMortality 
##                     6.838089e-03                    -1.688486e-01 
##              FertilityRate.nonNA                           Over60 
##                     1.373235e+00                     1.855136e-01 
##                       Population                Region.fctrAfrica 
##                    -6.290707e-09                    -1.763052e+00 
##              Region.fctrAmericas Region.fctrEastern Mediterranean 
##                     2.172714e+00                     1.882474e+00 
##       Region.fctrSouth-East Asia       Region.fctrWestern Pacific 
##                     7.393625e-01                     1.490571e+00 
##                          Under15 
##                    -2.450473e-01 
## [1] "myfit_mdl: train diagnostics complete: 2.952000 secs"
## [1] "myfit_mdl: predict complete: 3.065000 secs"
##                  id
## 1 All.X##rcv#glmnet
##                                                                                                                   feats
## 1 Over60,CellularSubscribers.nonNA,.rnorm,Population,Region.fctr,.pos,.pos.y,FertilityRate.nonNA,Under15,ChildMortality
##   max.nTuningRuns min.elapsedtime.everything min.elapsedtime.final
## 1              25                       1.59                 0.006
##   max.R.sq.fit min.RMSE.fit max.Adj.R.sq.fit max.R.sq.OOB min.RMSE.OOB
## 1    0.8998973     3.175766         0.892068     0.878346     3.221132
##   max.Adj.R.sq.OOB max.Rsquared.fit min.RMSESD.fit max.RsquaredSD.fit
## 1        0.8688312         0.889112      0.3435573         0.02328833
## [1] "myfit_mdl: exit: 3.073000 secs"
##                label step_major step_minor label_minor    bgn    end
## 3 fit.models_1_All.X          1          2      glmnet 34.474 37.552
## 4 fit.models_1_All.X          1          3         glm 37.553     NA
##   elapsed
## 3   3.078
## 4      NA
## [1] "myfit_mdl: enter: 0.000000 secs"
## [1] "fitting model: All.X##rcv#glm"
## [1] "    indepVar: Over60,CellularSubscribers.nonNA,.rnorm,Population,Region.fctr,.pos,.pos.y,FertilityRate.nonNA,Under15,ChildMortality"
## [1] "myfit_mdl: setup complete: 0.676000 secs"
## Aggregating results
## Fitting final model on full training set
## [1] "myfit_mdl: train complete: 1.711000 secs"

## 
## Call:
## NULL
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -8.7469  -1.5068   0.1917   1.9945   6.7723  
## 
## Coefficients: (1 not defined because of singularities)
##                                      Estimate Std. Error t value Pr(>|t|)
## (Intercept)                         7.710e+01  2.598e+00  29.672  < 2e-16
## .pos                               -7.451e-03  4.013e-03  -1.856  0.06503
## .pos.y                                     NA         NA      NA       NA
## .rnorm                              7.004e-02  2.264e-01   0.309  0.75744
## CellularSubscribers.nonNA           6.593e-03  7.296e-03   0.904  0.36742
## ChildMortality                     -1.732e-01  1.269e-02 -13.642  < 2e-16
## FertilityRate.nonNA                 1.766e+00  5.648e-01   3.127  0.00206
## Over60                              1.785e-01  7.245e-02   2.464  0.01467
## Population                         -1.733e-07  1.662e-06  -0.104  0.91711
## Region.fctrAfrica                  -1.609e+00  1.071e+00  -1.501  0.13498
## Region.fctrAmericas                 2.449e+00  8.416e-01   2.909  0.00408
## `Region.fctrEastern Mediterranean`  2.027e+00  1.067e+00   1.900  0.05906
## `Region.fctrSouth-East Asia`        1.085e+00  1.216e+00   0.892  0.37349
## `Region.fctrWestern Pacific`        1.724e+00  8.998e-01   1.915  0.05702
## Under15                            -2.931e-01  8.924e-02  -3.285  0.00123
##                                       
## (Intercept)                        ***
## .pos                               .  
## .pos.y                                
## .rnorm                                
## CellularSubscribers.nonNA             
## ChildMortality                     ***
## FertilityRate.nonNA                ** 
## Over60                             *  
## Population                            
## Region.fctrAfrica                     
## Region.fctrAmericas                ** 
## `Region.fctrEastern Mediterranean` .  
## `Region.fctrSouth-East Asia`          
## `Region.fctrWestern Pacific`       .  
## Under15                            ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for gaussian family taken to be 9.17023)
## 
##     Null deviance: 16546.0  on 193  degrees of freedom
## Residual deviance:  1650.6  on 180  degrees of freedom
## AIC: 995.91
## 
## Number of Fisher Scoring iterations: 2
## 
## [1] "myfit_mdl: train diagnostics complete: 2.404000 secs"
## Warning in predict.lm(object, newdata, se.fit, scale = 1, type =
## ifelse(type == : prediction from a rank-deficient fit may be misleading

## Warning in predict.lm(object, newdata, se.fit, scale = 1, type =
## ifelse(type == : prediction from a rank-deficient fit may be misleading

## [1] "myfit_mdl: predict complete: 2.455000 secs"
##               id
## 1 All.X##rcv#glm
##                                                                                                                   feats
## 1 Over60,CellularSubscribers.nonNA,.rnorm,Population,Region.fctr,.pos,.pos.y,FertilityRate.nonNA,Under15,ChildMortality
##   max.nTuningRuns min.elapsedtime.everything min.elapsedtime.final
## 1               1                       1.03                  0.01
##   max.R.sq.fit min.RMSE.fit min.aic.fit max.Adj.R.sq.fit max.R.sq.OOB
## 1    0.9002391     3.185692     995.914        0.8930342    0.8767941
##   min.RMSE.OOB max.Adj.R.sq.OOB max.Rsquared.fit min.RMSESD.fit
## 1     3.241612        0.8678959         0.888477      0.3501029
##   max.RsquaredSD.fit
## 1         0.02351873
## [1] "myfit_mdl: exit: 2.464000 secs"
# Check if other preProcess methods improve model performance
fit.models_1_chunk_df <- 
    myadd_chunk(fit.models_1_chunk_df, "fit.models_1_preProc", major.inc = FALSE,
                label.minor = "preProc")
##                  label step_major step_minor label_minor    bgn    end
## 4   fit.models_1_All.X          1          3         glm 37.553 40.026
## 5 fit.models_1_preProc          1          4     preProc 40.027     NA
##   elapsed
## 4   2.473
## 5      NA
mdl_id <- orderBy(get_model_sel_frmla(), glb_models_df)[1, "id"]
indepVar <- trim(unlist(strsplit(glb_models_df[glb_models_df$id == mdl_id,
                                                      "feats"], "[,]")))
method <- tail(unlist(strsplit(mdl_id, "[.]")), 1)
mdl_id_pfx <- paste0(head(unlist(strsplit(mdl_id, "[.]")), -1), collapse = ".")
if (!is.null(glbObsFitOutliers[[mdl_id_pfx]])) {
    fitobs_df <- glbObsFit[!(glbObsFit[, glbFeatsId] %in%
                                     glbObsFitOutliers[[mdl_id_pfx]]), ]
        print(sprintf("Outliers removed: %d", nrow(glbObsFit) - nrow(fitobs_df)))
        print(setdiff(glbObsFit[, glbFeatsId], fitobs_df[, glbFeatsId]))
    
} else fitobs_df <- glbObsFit

for (prePr in glb_preproc_methods) {   
    # The operations are applied in this order: 
    #   Box-Cox/Yeo-Johnson transformation, centering, scaling, range, imputation, PCA, ICA then spatial sign.
    
    ret_lst <- myfit_mdl(mdl_specs_lst=myinit_mdl_specs_lst(mdl_specs_lst=list(
            id.prefix=mdl_id_pfx, 
            type=glb_model_type, tune.df=glbMdlTuneParams,
            trainControl.method="repeatedcv",
            trainControl.number=glb_rcv_n_folds,
            trainControl.repeats=glb_rcv_n_repeats,
            trainControl.classProbs = glb_is_classification,
            trainControl.summaryFunction = glbMdlMetricSummaryFn,
            train.metric = glbMdlMetricSummary, 
            train.maximize = glbMdlMetricMaximize,    
            train.method=method, train.preProcess=prePr)),
            indepVar=indepVar, rsp_var=glb_rsp_var, 
            fit_df=fitobs_df, OOB_df=glbObsOOB)
}            
    
    # If (All|RFE).X.glm is less accurate than Low.Cor.X.glm
    #   check NA coefficients & filter appropriate terms in indepVar
#     if (method == "glm") {
#         orig_glm <- glb_models_lst[[paste0(mdl_id, ".", model_method)]]$finalModel
#         orig_glm <- glb_models_lst[["All.X.glm"]]$finalModel; print(summary(orig_glm))
#         orig_glm <- glb_models_lst[["RFE.X.glm"]]$finalModel; print(summary(orig_glm))
#           require(car)
#           vif_orig_glm <- vif(orig_glm); print(vif_orig_glm)
#           # if vif errors out with "there are aliased coefficients in the model"
#               alias_orig_glm <- alias(orig_glm); alias_complete_orig_glm <- (alias_orig_glm$Complete > 0); alias_complete_orig_glm <- alias_complete_orig_glm[rowSums(alias_complete_orig_glm) > 0, colSums(alias_complete_orig_glm) > 0]; print(alias_complete_orig_glm)
#           print(vif_orig_glm[!is.na(vif_orig_glm) & (vif_orig_glm == Inf)])
#           print(which.max(vif_orig_glm))
#           print(sort(vif_orig_glm[vif_orig_glm >= 1.0e+03], decreasing=TRUE))
#           glbObsFit[c(1143, 3637, 3953, 4105), c("UniqueID", "Popular", "H.P.quandary", "Headline")]
#           glb_feats_df[glb_feats_df$id %in% grep("[HSA]\\.chrs.n.log", glb_feats_df$id, value=TRUE) | glb_feats_df$cor.high.X %in%    grep("[HSA]\\.chrs.n.log", glb_feats_df$id, value=TRUE), ]
#           all.equal(glbObsAll$S.chrs.uppr.n.log, glbObsAll$A.chrs.uppr.n.log)
#           cor(glbObsAll$S.T.herald, glbObsAll$S.T.tribun)
#           mydspObs(Abstract.contains="[Dd]iar", cols=("Abstract"), all=TRUE)
#           subset(glb_feats_df, cor.y.abs <= glb_feats_df[glb_feats_df$id == ".rnorm", "cor.y.abs"])
#         corxx_mtrx <- cor(data.matrix(glbObsAll[, setdiff(names(glbObsAll), myfind_chr_cols_df(glbObsAll))]), use="pairwise.complete.obs"); abs_corxx_mtrx <- abs(corxx_mtrx); diag(abs_corxx_mtrx) <- 0
#           which.max(abs_corxx_mtrx["S.T.tribun", ])
#           abs_corxx_mtrx["A.npnct08.log", "S.npnct08.log"]
#         step_glm <- step(orig_glm)
#     }
    # Since caret does not optimize rpart well
#     if (method == "rpart")
#         ret_lst <- myfit_mdl(mdl_id=paste0(mdl_id_pfx, ".cp.0"), model_method=method,
#                                 indepVar=indepVar,
#                                 model_type=glb_model_type,
#                                 rsp_var=glb_rsp_var,
#                                 fit_df=glbObsFit, OOB_df=glbObsOOB,        
#             n_cv_folds=0, tune_models_df=data.frame(parameter="cp", min=0.0, max=0.0, by=0.1))

# User specified
#   Ensure at least 2 vars in each regression; else varImp crashes
# sav_models_lst <- glb_models_lst; sav_models_df <- glb_models_df; sav_featsimp_df <- glb_featsimp_df; all.equal(sav_featsimp_df, glb_featsimp_df)
# glb_models_lst <- sav_models_lst; glb_models_df <- sav_models_df; glm_featsimp_df <- sav_featsimp_df

    # easier to exclude features
# require(gdata) # needed for trim
# mdl_id <- "";
# indepVar <- head(subset(glb_models_df, grepl("All\\.X\\.", mdl_id), select=feats)
#                         , 1)[, "feats"]
# indepVar <- trim(unlist(strsplit(indepVar, "[,]")))
# indepVar <- setdiff(indepVar, ".rnorm")

    # easier to include features
#stop(here"); sav_models_df <- glb_models_df; glb_models_df <- sav_models_df
# !_sp
# mdl_id <- "csm"; indepVar <- c(NULL
#     ,"prdline.my.fctr", "prdline.my.fctr:.clusterid.fctr"
#     ,"prdline.my.fctr*biddable"
#     #,"prdline.my.fctr*startprice.log"
#     #,"prdline.my.fctr*startprice.diff"    
#     ,"prdline.my.fctr*condition.fctr"
#     ,"prdline.my.fctr*D.terms.post.stop.n"
#     #,"prdline.my.fctr*D.terms.post.stem.n"
#     ,"prdline.my.fctr*cellular.fctr"    
# #    ,"<feat1>:<feat2>"
#                                            )
# for (method in glbMdlMethods) {
#     ret_lst <- myfit_mdl(mdl_id=mdl_id, model_method=method,
#                                 indepVar=indepVar,
#                                 model_type=glb_model_type,
#                                 rsp_var=glb_rsp_var,
#                                 fit_df=glbObsFit, OOB_df=glbObsOOB,
#                     n_cv_folds=glb_rcv_n_folds, tune_models_df=glbMdlTuneParams)
#     csm_mdl_id <- paste0(mdl_id, ".", method)
#     csm_featsimp_df <- myget_feats_importance(glb_models_lst[[paste0(mdl_id, ".",
#                                                                      method)]]);               print(head(csm_featsimp_df))
# }
###

# Ntv.1.lm <- lm(reformulate(indepVar, glb_rsp_var), glbObsTrn); print(summary(Ntv.1.lm))

#glb_models_df[, "max.Accuracy.OOB", FALSE]
#varImp(glb_models_lst[["Low.cor.X.glm"]])
#orderBy(~ -Overall, varImp(glb_models_lst[["All.X.2.glm"]])$imp)
#orderBy(~ -Overall, varImp(glb_models_lst[["All.X.3.glm"]])$imp)
#glb_feats_df[grepl("npnct28", glb_feats_df$id), ]

    # User specified bivariate models
#     indepVar_lst <- list()
#     for (feat in setdiff(names(glbObsFit), 
#                          union(glb_rsp_var, glbFeatsExclude)))
#         indepVar_lst[["feat"]] <- feat

    # User specified combinatorial models
#     indepVar_lst <- list()
#     combn_mtrx <- combn(c("<feat1_name>", "<feat2_name>", "<featn_name>"), 
#                           <num_feats_to_choose>)
#     for (combn_ix in 1:ncol(combn_mtrx))
#         #print(combn_mtrx[, combn_ix])
#         indepVar_lst[[combn_ix]] <- combn_mtrx[, combn_ix]
    
    # template for myfit_mdl
    #   rf is hard-coded in caret to recognize only Accuracy / Kappa evaluation metrics
    #       only for OOB in trainControl ?
    
#     ret_lst <- myfit_mdl_fn(mdl_id=paste0(mdl_id_pfx, ""), model_method=method,
#                             indepVar=indepVar,
#                             rsp_var=glb_rsp_var,
#                             fit_df=glbObsFit, OOB_df=glbObsOOB,
#                             n_cv_folds=glb_rcv_n_folds, tune_models_df=glbMdlTuneParams,
#                             model_loss_mtrx=glbMdlMetric_terms,
#                             model_summaryFunction=glbMdlMetricSummaryFn,
#                             model_metric=glbMdlMetricSummary,
#                             model_metric_maximize=glbMdlMetricMaximize)

# Simplify a model
# fit_df <- glbObsFit; glb_mdl <- step(<complex>_mdl)

# Non-caret models
#     rpart_area_mdl <- rpart(reformulate("Area", response=glb_rsp_var), 
#                                data=glbObsFit, #method="class", 
#                                control=rpart.control(cp=0.12),
#                            parms=list(loss=glbMdlMetric_terms))
#     print("rpart_sel_wlm_mdl"); prp(rpart_sel_wlm_mdl)
# 

print(glb_models_df)
##                                                              id
## Max.cor.Y.rcv.1X1###glmnet           Max.cor.Y.rcv.1X1###glmnet
## Max.cor.Y##rcv#rpart                       Max.cor.Y##rcv#rpart
## Interact.High.cor.Y##rcv#glmnet Interact.High.cor.Y##rcv#glmnet
## Low.cor.X##rcv#glmnet                     Low.cor.X##rcv#glmnet
## All.X##rcv#glmnet                             All.X##rcv#glmnet
## All.X##rcv#glm                                   All.X##rcv#glm
##                                                                                                                                                 feats
## Max.cor.Y.rcv.1X1###glmnet                                                                                   ChildMortality,CellularSubscribers.nonNA
## Max.cor.Y##rcv#rpart                                                                                         ChildMortality,CellularSubscribers.nonNA
## Interact.High.cor.Y##rcv#glmnet                         ChildMortality,CellularSubscribers.nonNA,ChildMortality:Under15,ChildMortality:ChildMortality
## Low.cor.X##rcv#glmnet           Over60,CellularSubscribers.nonNA,.rnorm,Population,Region.fctr,.pos,.pos.y,FertilityRate.nonNA,Under15,ChildMortality
## All.X##rcv#glmnet               Over60,CellularSubscribers.nonNA,.rnorm,Population,Region.fctr,.pos,.pos.y,FertilityRate.nonNA,Under15,ChildMortality
## All.X##rcv#glm                  Over60,CellularSubscribers.nonNA,.rnorm,Population,Region.fctr,.pos,.pos.y,FertilityRate.nonNA,Under15,ChildMortality
##                                 max.nTuningRuns min.elapsedtime.everything
## Max.cor.Y.rcv.1X1###glmnet                    0                      0.762
## Max.cor.Y##rcv#rpart                          5                      1.234
## Interact.High.cor.Y##rcv#glmnet              25                      1.561
## Low.cor.X##rcv#glmnet                        25                      1.566
## All.X##rcv#glmnet                            25                      1.590
## All.X##rcv#glm                                1                      1.030
##                                 min.elapsedtime.final max.R.sq.fit
## Max.cor.Y.rcv.1X1###glmnet                      0.011    0.8565517
## Max.cor.Y##rcv#rpart                            0.010    0.8845143
## Interact.High.cor.Y##rcv#glmnet                 0.005    0.8636280
## Low.cor.X##rcv#glmnet                           0.007    0.8998973
## All.X##rcv#glmnet                               0.006    0.8998973
## All.X##rcv#glm                                  0.010    0.9002391
##                                 min.RMSE.fit max.Adj.R.sq.fit max.R.sq.OOB
## Max.cor.Y.rcv.1X1###glmnet          3.497785        0.8550496    0.8573102
## Max.cor.Y##rcv#rpart                3.612457               NA    0.8845143
## Interact.High.cor.Y##rcv#glmnet     3.508182        0.8614748    0.8641454
## Low.cor.X##rcv#glmnet               3.175766        0.8920680    0.8783460
## All.X##rcv#glmnet                   3.175766        0.8920680    0.8783460
## All.X##rcv#glm                      3.185692        0.8930342    0.8767941
##                                 min.RMSE.OOB max.Adj.R.sq.OOB
## Max.cor.Y.rcv.1X1###glmnet          3.488525        0.8558161
## Max.cor.Y##rcv#rpart                3.138409               NA
## Interact.High.cor.Y##rcv#glmnet     3.403945        0.8620004
## Low.cor.X##rcv#glmnet               3.221132        0.8688312
## All.X##rcv#glmnet                   3.221132        0.8688312
## All.X##rcv#glm                      3.241612        0.8678959
##                                 max.Rsquared.fit min.RMSESD.fit
## Max.cor.Y.rcv.1X1###glmnet                    NA             NA
## Max.cor.Y##rcv#rpart                   0.8507488      0.5005967
## Interact.High.cor.Y##rcv#glmnet        0.8648804      0.3711338
## Low.cor.X##rcv#glmnet                  0.8891120      0.3435573
## All.X##rcv#glmnet                      0.8891120      0.3435573
## All.X##rcv#glm                         0.8884770      0.3501029
##                                 max.RsquaredSD.fit min.aic.fit
## Max.cor.Y.rcv.1X1###glmnet                      NA          NA
## Max.cor.Y##rcv#rpart                    0.04168522          NA
## Interact.High.cor.Y##rcv#glmnet         0.02530595          NA
## Low.cor.X##rcv#glmnet                   0.02328833          NA
## All.X##rcv#glmnet                       0.02328833          NA
## All.X##rcv#glm                          0.02351873     995.914
rm(ret_lst)
fit.models_1_chunk_df <- 
    myadd_chunk(fit.models_1_chunk_df, "fit.models_1_end", major.inc = FALSE,
                label.minor = "teardown")
##                  label step_major step_minor label_minor    bgn    end
## 5 fit.models_1_preProc          1          4     preProc 40.027 40.079
## 6     fit.models_1_end          1          5    teardown 40.079     NA
##   elapsed
## 5   0.052
## 6      NA
glb_chunks_df <- myadd_chunk(glb_chunks_df, "fit.models", major.inc = FALSE)
##         label step_major step_minor label_minor    bgn    end elapsed
## 17 fit.models          8          1           1 33.377 40.086   6.709
## 18 fit.models          8          2           2 40.087     NA      NA
fit.models_2_chunk_df <- 
    myadd_chunk(NULL, "fit.models_2_bgn", label.minor = "setup")
##              label step_major step_minor label_minor    bgn end elapsed
## 1 fit.models_2_bgn          1          0       setup 41.466  NA      NA
plt_models_df <- glb_models_df[, -grep("SD|Upper|Lower", names(glb_models_df))]
for (var in grep("^min.", names(plt_models_df), value=TRUE)) {
    plt_models_df[, sub("min.", "inv.", var)] <- 
        #ifelse(all(is.na(tmp <- plt_models_df[, var])), NA, 1.0 / tmp)
        1.0 / plt_models_df[, var]
    plt_models_df <- plt_models_df[ , -grep(var, names(plt_models_df))]
}
print(plt_models_df)
##                                                              id
## Max.cor.Y.rcv.1X1###glmnet           Max.cor.Y.rcv.1X1###glmnet
## Max.cor.Y##rcv#rpart                       Max.cor.Y##rcv#rpart
## Interact.High.cor.Y##rcv#glmnet Interact.High.cor.Y##rcv#glmnet
## Low.cor.X##rcv#glmnet                     Low.cor.X##rcv#glmnet
## All.X##rcv#glmnet                             All.X##rcv#glmnet
## All.X##rcv#glm                                   All.X##rcv#glm
##                                                                                                                                                 feats
## Max.cor.Y.rcv.1X1###glmnet                                                                                   ChildMortality,CellularSubscribers.nonNA
## Max.cor.Y##rcv#rpart                                                                                         ChildMortality,CellularSubscribers.nonNA
## Interact.High.cor.Y##rcv#glmnet                         ChildMortality,CellularSubscribers.nonNA,ChildMortality:Under15,ChildMortality:ChildMortality
## Low.cor.X##rcv#glmnet           Over60,CellularSubscribers.nonNA,.rnorm,Population,Region.fctr,.pos,.pos.y,FertilityRate.nonNA,Under15,ChildMortality
## All.X##rcv#glmnet               Over60,CellularSubscribers.nonNA,.rnorm,Population,Region.fctr,.pos,.pos.y,FertilityRate.nonNA,Under15,ChildMortality
## All.X##rcv#glm                  Over60,CellularSubscribers.nonNA,.rnorm,Population,Region.fctr,.pos,.pos.y,FertilityRate.nonNA,Under15,ChildMortality
##                                 max.nTuningRuns max.R.sq.fit
## Max.cor.Y.rcv.1X1###glmnet                    0    0.8565517
## Max.cor.Y##rcv#rpart                          5    0.8845143
## Interact.High.cor.Y##rcv#glmnet              25    0.8636280
## Low.cor.X##rcv#glmnet                        25    0.8998973
## All.X##rcv#glmnet                            25    0.8998973
## All.X##rcv#glm                                1    0.9002391
##                                 max.Adj.R.sq.fit max.R.sq.OOB
## Max.cor.Y.rcv.1X1###glmnet             0.8550496    0.8573102
## Max.cor.Y##rcv#rpart                          NA    0.8845143
## Interact.High.cor.Y##rcv#glmnet        0.8614748    0.8641454
## Low.cor.X##rcv#glmnet                  0.8920680    0.8783460
## All.X##rcv#glmnet                      0.8920680    0.8783460
## All.X##rcv#glm                         0.8930342    0.8767941
##                                 max.Adj.R.sq.OOB max.Rsquared.fit
## Max.cor.Y.rcv.1X1###glmnet             0.8558161               NA
## Max.cor.Y##rcv#rpart                          NA        0.8507488
## Interact.High.cor.Y##rcv#glmnet        0.8620004        0.8648804
## Low.cor.X##rcv#glmnet                  0.8688312        0.8891120
## All.X##rcv#glmnet                      0.8688312        0.8891120
## All.X##rcv#glm                         0.8678959        0.8884770
##                                 inv.elapsedtime.everything
## Max.cor.Y.rcv.1X1###glmnet                       1.3123360
## Max.cor.Y##rcv#rpart                             0.8103728
## Interact.High.cor.Y##rcv#glmnet                  0.6406150
## Low.cor.X##rcv#glmnet                            0.6385696
## All.X##rcv#glmnet                                0.6289308
## All.X##rcv#glm                                   0.9708738
##                                 inv.elapsedtime.final inv.RMSE.fit
## Max.cor.Y.rcv.1X1###glmnet                   90.90909    0.2858952
## Max.cor.Y##rcv#rpart                        100.00000    0.2768199
## Interact.High.cor.Y##rcv#glmnet             200.00000    0.2850479
## Low.cor.X##rcv#glmnet                       142.85714    0.3148846
## All.X##rcv#glmnet                           166.66667    0.3148846
## All.X##rcv#glm                              100.00000    0.3139035
##                                 inv.RMSE.OOB inv.aic.fit
## Max.cor.Y.rcv.1X1###glmnet         0.2866541          NA
## Max.cor.Y##rcv#rpart               0.3186328          NA
## Interact.High.cor.Y##rcv#glmnet    0.2937768          NA
## Low.cor.X##rcv#glmnet              0.3104499          NA
## All.X##rcv#glmnet                  0.3104499          NA
## All.X##rcv#glm                     0.3084885 0.001004103
# print(myplot_radar(radar_inp_df=plt_models_df))
# print(myplot_radar(radar_inp_df=subset(plt_models_df, 
#         !(mdl_id %in% grep("random|MFO", plt_models_df$id, value=TRUE)))))

# Compute CI for <metric>SD
glb_models_df <- mutate(glb_models_df, 
                max.df = ifelse(max.nTuningRuns > 1, max.nTuningRuns - 1, NA),
                min.sd2ci.scaler = ifelse(is.na(max.df), NA, qt(0.975, max.df)))
for (var in grep("SD", names(glb_models_df), value=TRUE)) {
    # Does CI alredy exist ?
    var_components <- unlist(strsplit(var, "SD"))
    varActul <- paste0(var_components[1],          var_components[2])
    varUpper <- paste0(var_components[1], "Upper", var_components[2])
    varLower <- paste0(var_components[1], "Lower", var_components[2])
    if (varUpper %in% names(glb_models_df)) {
        warning(varUpper, " already exists in glb_models_df")
        # Assuming Lower also exists
        next
    }    
    print(sprintf("var:%s", var))
    # CI is dependent on sample size in t distribution; df=n-1
    glb_models_df[, varUpper] <- glb_models_df[, varActul] + 
        glb_models_df[, "min.sd2ci.scaler"] * glb_models_df[, var]
    glb_models_df[, varLower] <- glb_models_df[, varActul] - 
        glb_models_df[, "min.sd2ci.scaler"] * glb_models_df[, var]
}
## [1] "var:min.RMSESD.fit"
## [1] "var:max.RsquaredSD.fit"
# Plot metrics with CI
plt_models_df <- glb_models_df[, "id", FALSE]
pltCI_models_df <- glb_models_df[, "id", FALSE]
for (var in grep("Upper", names(glb_models_df), value=TRUE)) {
    var_components <- unlist(strsplit(var, "Upper"))
    col_name <- unlist(paste(var_components, collapse=""))
    plt_models_df[, col_name] <- glb_models_df[, col_name]
    for (name in paste0(var_components[1], c("Upper", "Lower"), var_components[2]))
        pltCI_models_df[, name] <- glb_models_df[, name]
}

build_statsCI_data <- function(plt_models_df) {
    mltd_models_df <- melt(plt_models_df, id.vars="id")
    mltd_models_df$data <- sapply(1:nrow(mltd_models_df), 
        function(row_ix) tail(unlist(strsplit(as.character(
            mltd_models_df[row_ix, "variable"]), "[.]")), 1))
    mltd_models_df$label <- sapply(1:nrow(mltd_models_df), 
        function(row_ix) head(unlist(strsplit(as.character(
            mltd_models_df[row_ix, "variable"]), 
            paste0(".", mltd_models_df[row_ix, "data"]))), 1))
    #print(mltd_models_df)
    
    return(mltd_models_df)
}
mltd_models_df <- build_statsCI_data(plt_models_df)

mltdCI_models_df <- melt(pltCI_models_df, id.vars="id")
for (row_ix in 1:nrow(mltdCI_models_df)) {
    for (type in c("Upper", "Lower")) {
        if (length(var_components <- unlist(strsplit(
                as.character(mltdCI_models_df[row_ix, "variable"]), type))) > 1) {
            #print(sprintf("row_ix:%d; type:%s; ", row_ix, type))
            mltdCI_models_df[row_ix, "label"] <- var_components[1]
            mltdCI_models_df[row_ix, "data"] <- 
                unlist(strsplit(var_components[2], "[.]"))[2]
            mltdCI_models_df[row_ix, "type"] <- type
            break
        }
    }    
}
wideCI_models_df <- reshape(subset(mltdCI_models_df, select=-variable), 
                            timevar="type", 
        idvar=setdiff(names(mltdCI_models_df), c("type", "value", "variable")), 
                            direction="wide")
#print(wideCI_models_df)
mrgdCI_models_df <- merge(wideCI_models_df, mltd_models_df, all.x=TRUE)
#print(mrgdCI_models_df)

# Merge stats back in if CIs don't exist
goback_vars <- c()
for (var in unique(mltd_models_df$label)) {
    for (type in unique(mltd_models_df$data)) {
        var_type <- paste0(var, ".", type)
        # if this data is already present, next
        if (var_type %in% unique(paste(mltd_models_df$label, mltd_models_df$data,
                                       sep=".")))
            next
        #print(sprintf("var_type:%s", var_type))
        goback_vars <- c(goback_vars, var_type)
    }
}

if (length(goback_vars) > 0) {
    mltd_goback_df <- build_statsCI_data(glb_models_df[, c("id", goback_vars)])
    mltd_models_df <- rbind(mltd_models_df, mltd_goback_df)
}

# mltd_models_df <- merge(mltd_models_df, glb_models_df[, c("id", "model_method")], 
#                         all.x=TRUE)

png(paste0(glbOut$pfx, "models_bar.png"), width=480*3, height=480*2)
#print(gp <- myplot_bar(mltd_models_df, "id", "value", colorcol_name="model_method") + 
print(gp <- myplot_bar(df=mltd_models_df, xcol_name="id", ycol_names="value") + 
        geom_errorbar(data=mrgdCI_models_df, 
            mapping=aes(x=mdl_id, ymax=value.Upper, ymin=value.Lower), width=0.5) + 
          facet_grid(label ~ data, scales="free") + 
          theme(axis.text.x = element_text(angle = 90,vjust = 0.5)))
## Warning: Removed 1 rows containing missing values (position_stack).
## Warning: Removed 4 rows containing missing values (geom_errorbar).
dev.off()
## quartz_off_screen 
##                 2
print(gp)
## Warning: Removed 1 rows containing missing values (position_stack).

## Warning: Removed 4 rows containing missing values (geom_errorbar).

dsp_models_cols <- c("id", 
                    glbMdlMetricsEval[glbMdlMetricsEval %in% names(glb_models_df)],
                    grep("opt.", names(glb_models_df), fixed = TRUE, value = TRUE)) 
# if (glb_is_classification && glb_is_binomial) 
#     dsp_models_cols <- c(dsp_models_cols, "opt.prob.threshold.OOB")
print(dsp_models_df <- orderBy(get_model_sel_frmla(), glb_models_df)[, dsp_models_cols])
##                                id min.RMSE.OOB max.R.sq.OOB
## 2            Max.cor.Y##rcv#rpart     3.138409    0.8845143
## 4           Low.cor.X##rcv#glmnet     3.221132    0.8783460
## 5               All.X##rcv#glmnet     3.221132    0.8783460
## 6                  All.X##rcv#glm     3.241612    0.8767941
## 3 Interact.High.cor.Y##rcv#glmnet     3.403945    0.8641454
## 1      Max.cor.Y.rcv.1X1###glmnet     3.488525    0.8573102
##   max.Adj.R.sq.fit min.RMSE.fit
## 2               NA     3.612457
## 4        0.8920680     3.175766
## 5        0.8920680     3.175766
## 6        0.8930342     3.185692
## 3        0.8614748     3.508182
## 1        0.8550496     3.497785
# print(myplot_radar(radar_inp_df = dsp_models_df))
print("Metrics used for model selection:"); print(get_model_sel_frmla())
## [1] "Metrics used for model selection:"
## ~+min.RMSE.OOB - max.R.sq.OOB - max.Adj.R.sq.fit + min.RMSE.fit
## <environment: 0x7fe9530af190>
print(sprintf("Best model id: %s", dsp_models_df[1, "id"]))
## [1] "Best model id: Max.cor.Y##rcv#rpart"
glb_get_predictions <- function(df, mdl_id, rsp_var, prob_threshold_def=NULL, verbose=FALSE) {
    mdl <- glb_models_lst[[mdl_id]]
    
    clmnNames <- mygetPredictIds(rsp_var, mdl_id)
    predct_var_name <- clmnNames$value        
    predct_prob_var_name <- clmnNames$prob
    predct_accurate_var_name <- clmnNames$is.acc
    predct_error_var_name <- clmnNames$err
    predct_erabs_var_name <- clmnNames$err.abs

    if (glb_is_regression) {
        df[, predct_var_name] <- predict(mdl, newdata=df, type="raw")
        if (verbose) print(myplot_scatter(df, glb_rsp_var, predct_var_name) + 
                  facet_wrap(reformulate(glbFeatsCategory), scales = "free") + 
                  stat_smooth(method="glm"))

        df[, predct_error_var_name] <- df[, predct_var_name] - df[, glb_rsp_var]
        if (verbose) print(myplot_scatter(df, predct_var_name, predct_error_var_name) + 
                  #facet_wrap(reformulate(glbFeatsCategory), scales = "free") + 
                  stat_smooth(method="auto"))
        if (verbose) print(myplot_scatter(df, glb_rsp_var, predct_error_var_name) + 
                  #facet_wrap(reformulate(glbFeatsCategory), scales = "free") + 
                  stat_smooth(method="glm"))
        
        df[, predct_erabs_var_name] <- abs(df[, predct_error_var_name])
        if (verbose) print(head(orderBy(reformulate(c("-", predct_erabs_var_name)), df)))
        
        df[, predct_accurate_var_name] <- (df[, glb_rsp_var] == df[, predct_var_name])
    }

    if (glb_is_classification && glb_is_binomial) {
        prob_threshold <- glb_models_df[glb_models_df$id == mdl_id, 
                                        "opt.prob.threshold.OOB"]
        if (is.null(prob_threshold) || is.na(prob_threshold)) {
            warning("Using default probability threshold: ", prob_threshold_def)
            if (is.null(prob_threshold <- prob_threshold_def))
                stop("Default probability threshold is NULL")
        }
        
        df[, predct_prob_var_name] <- predict(mdl, newdata = df, type = "prob")[, 2]
        df[, predct_var_name] <- 
                factor(levels(df[, glb_rsp_var])[
                    (df[, predct_prob_var_name] >=
                        prob_threshold) * 1 + 1], levels(df[, glb_rsp_var]))
    
#         if (verbose) print(myplot_scatter(df, glb_rsp_var, predct_var_name) + 
#                   facet_wrap(reformulate(glbFeatsCategory), scales = "free") + 
#                   stat_smooth(method="glm"))

        df[, predct_error_var_name] <- df[, predct_var_name] != df[, glb_rsp_var]
#         if (verbose) print(myplot_scatter(df, predct_var_name, predct_error_var_name) + 
#                   #facet_wrap(reformulate(glbFeatsCategory), scales = "free") + 
#                   stat_smooth(method="auto"))
#         if (verbose) print(myplot_scatter(df, glb_rsp_var, predct_error_var_name) + 
#                   #facet_wrap(reformulate(glbFeatsCategory), scales = "free") + 
#                   stat_smooth(method="glm"))
        
        # if prediction is a TP (true +ve), measure distance from 1.0
        tp <- which((df[, predct_var_name] == df[, glb_rsp_var]) &
                    (df[, predct_var_name] == levels(df[, glb_rsp_var])[2]))
        df[tp, predct_erabs_var_name] <- abs(1 - df[tp, predct_prob_var_name])
        #rowIx <- which.max(df[tp, predct_erabs_var_name]); df[tp, c(glbFeatsId, glb_rsp_var, predct_var_name, predct_prob_var_name, predct_erabs_var_name)][rowIx, ]
        
        # if prediction is a TN (true -ve), measure distance from 0.0
        tn <- which((df[, predct_var_name] == df[, glb_rsp_var]) &
                    (df[, predct_var_name] == levels(df[, glb_rsp_var])[1]))
        df[tn, predct_erabs_var_name] <- abs(0 - df[tn, predct_prob_var_name])
        #rowIx <- which.max(df[tn, predct_erabs_var_name]); df[tn, c(glbFeatsId, glb_rsp_var, predct_var_name, predct_prob_var_name, predct_erabs_var_name)][rowIx, ]
        
        # if prediction is a FP (flse +ve), measure distance from 0.0
        fp <- which((df[, predct_var_name] != df[, glb_rsp_var]) &
                    (df[, predct_var_name] == levels(df[, glb_rsp_var])[2]))
        df[fp, predct_erabs_var_name] <- abs(0 - df[fp, predct_prob_var_name])
        #rowIx <- which.max(df[fp, predct_erabs_var_name]); df[fp, c(glbFeatsId, glb_rsp_var, predct_var_name, predct_prob_var_name, predct_erabs_var_name)][rowIx, ]
        
        # if prediction is a FN (flse -ve), measure distance from 1.0
        fn <- which((df[, predct_var_name] != df[, glb_rsp_var]) &
                    (df[, predct_var_name] == levels(df[, glb_rsp_var])[1]))
        df[fn, predct_erabs_var_name] <- abs(1 - df[fn, predct_prob_var_name])
        #rowIx <- which.max(df[fn, predct_erabs_var_name]); df[fn, c(glbFeatsId, glb_rsp_var, predct_var_name, predct_prob_var_name, predct_erabs_var_name)][rowIx, ]

        
        if (verbose) print(head(orderBy(reformulate(c("-", predct_erabs_var_name)), df)))
        
        df[, predct_accurate_var_name] <- (df[, glb_rsp_var] == df[, predct_var_name])
    }    
    
    if (glb_is_classification && !glb_is_binomial) {
        df[, predct_var_name] <- predict(mdl, newdata = df, type = "raw")
        probCls <- predict(mdl, newdata = df, type = "prob")        
        df[, predct_prob_var_name] <- NA
        for (cls in names(probCls)) {
            mask <- (df[, predct_var_name] == cls)
            df[mask, predct_prob_var_name] <- probCls[mask, cls]
        }    
        if (verbose) print(myplot_histogram(df, predct_prob_var_name, 
                                            fill_col_name = predct_var_name))
        if (verbose) print(myplot_histogram(df, predct_prob_var_name, 
                                            facet_frmla = paste0("~", glb_rsp_var)))
        
        df[, predct_error_var_name] <- df[, predct_var_name] != df[, glb_rsp_var]
        
        # if prediction is erroneous, measure predicted class prob from actual class prob
        df[, predct_erabs_var_name] <- 0
        for (cls in names(probCls)) {
            mask <- (df[, glb_rsp_var] == cls) & (df[, predct_error_var_name])
            df[mask, predct_erabs_var_name] <- probCls[mask, cls]
        }    

        df[, predct_accurate_var_name] <- (df[, glb_rsp_var] == df[, predct_var_name])        
    }

    return(df)
}    

#stop(here"); glb2Sav(); glbObsAll <- savObsAll; glbObsTrn <- savObsTrn; glbObsFit <- savObsFit; glbObsOOB <- savObsOOB; sav_models_df <- glb_models_df; glb_models_df <- sav_models_df; glb_featsimp_df <- sav_featsimp_df    

myget_category_stats <- function(obs_df, mdl_id, label) {
    require(dplyr)
    require(lazyeval)
    
    predct_var_name <- mygetPredictIds(glb_rsp_var, mdl_id)$value        
    predct_error_var_name <- mygetPredictIds(glb_rsp_var, mdl_id)$err.abs
    
    if (!predct_var_name %in% names(obs_df))
        obs_df <- glb_get_predictions(obs_df, mdl_id, glb_rsp_var)
    
    tmp_obs_df <- obs_df[, c(glbFeatsCategory, glb_rsp_var, 
                             predct_var_name, predct_error_var_name)]
#     tmp_obs_df <- obs_df %>%
#         dplyr::select_(glbFeatsCategory, glb_rsp_var, predct_var_name, predct_error_var_name) 
    #dplyr::rename(startprice.log10.predict.RFE.X.glmnet.err=error_abs_OOB)
    names(tmp_obs_df)[length(names(tmp_obs_df))] <- paste0("err.abs.", label)
    
    ret_ctgry_df <- tmp_obs_df %>%
        dplyr::group_by_(glbFeatsCategory) %>%
        dplyr::summarise_(#interp(~sum(abs(var)), var=as.name(glb_rsp_var)), 
            interp(~sum(var), var=as.name(paste0("err.abs.", label))), 
            interp(~mean(var), var=as.name(paste0("err.abs.", label))),
            interp(~n()))
    names(ret_ctgry_df) <- c(glbFeatsCategory, 
                             #paste0(glb_rsp_var, ".abs.", label, ".sum"),
                             paste0("err.abs.", label, ".sum"),                             
                             paste0("err.abs.", label, ".mean"), 
                             paste0(".n.", label))
    ret_ctgry_df <- dplyr::ungroup(ret_ctgry_df)
    #colSums(ret_ctgry_df[, -grep(glbFeatsCategory, names(ret_ctgry_df))])
    
    return(ret_ctgry_df)    
}
#print(colSums((ctgry_df <- myget_category_stats(obs_df=glbObsFit, mdl_id="", label="fit"))[, -grep(glbFeatsCategory, names(ctgry_df))]))

if (!is.null(glb_mdl_ensemble)) {
    fit.models_2_chunk_df <- myadd_chunk(fit.models_2_chunk_df, 
                            paste0("fit.models_2_", mdl_id_pfx), major.inc = TRUE, 
                                                label.minor = "ensemble")
    
    mdl_id_pfx <- "Ensemble"

    if (#(glb_is_regression) | 
        ((glb_is_classification) & (!glb_is_binomial)))
        stop("Ensemble models not implemented yet for multinomial classification")
    
    mygetEnsembleAutoMdlIds <- function() {
        tmp_models_df <- orderBy(get_model_sel_frmla(), glb_models_df)
        row.names(tmp_models_df) <- tmp_models_df$id
        mdl_threshold_pos <- 
            min(which(grepl("MFO|Random|Baseline", tmp_models_df$id))) - 1
        mdlIds <- tmp_models_df$id[1:mdl_threshold_pos]
        return(mdlIds[!grepl("Ensemble", mdlIds)])
    }
    
    if (glb_mdl_ensemble == "auto") {
        glb_mdl_ensemble <- mygetEnsembleAutoMdlIds()
        mdl_id_pfx <- paste0(mdl_id_pfx, ".auto")        
    } else if (grepl("^%<d-%", glb_mdl_ensemble)) {
        glb_mdl_ensemble <- eval(parse(text =
                        str_trim(unlist(strsplit(glb_mdl_ensemble, "%<d-%"))[2])))
    }
    
    for (mdl_id in glb_mdl_ensemble) {
        if (!(mdl_id %in% names(glb_models_lst))) {
            warning("Model ", mdl_id, " in glb_model_ensemble not found !")
            next
        }
        glbObsFit <- glb_get_predictions(df = glbObsFit, mdl_id, glb_rsp_var)
        glbObsOOB <- glb_get_predictions(df = glbObsOOB, mdl_id, glb_rsp_var)
    }
    
#mdl_id_pfx <- "Ensemble.RFE"; mdlId <- paste0(mdl_id_pfx, ".glmnet")
#glb_mdl_ensemble <- gsub(mygetPredictIds$value, "", grep("RFE\\.X\\.(?!Interact)", row.names(glb_featsimp_df), perl = TRUE, value = TRUE), fixed = TRUE)
#varImp(glb_models_lst[[mdlId]])
    
#cor_df <- data.frame(cor=cor(glbObsFit[, glb_rsp_var], glbObsFit[, paste(mygetPredictIds$value, glb_mdl_ensemble)], use="pairwise.complete.obs"))
#glbObsFit <- glb_get_predictions(df=glbObsFit, "Ensemble.glmnet", glb_rsp_var);print(colSums((ctgry_df <- myget_category_stats(obs_df=glbObsFit, mdl_id="Ensemble.glmnet", label="fit"))[, -grep(glbFeatsCategory, names(ctgry_df))]))
    
    ### bid0_sp
    #  Better than MFO; models.n=28; min.RMSE.fit=0.0521233; err.abs.fit.sum=7.3631895
    #  old: Top x from auto; models.n= 5; min.RMSE.fit=0.06311047; err.abs.fit.sum=9.5937080
    #  RFE only ;       models.n=16; min.RMSE.fit=0.05148588; err.abs.fit.sum=7.2875091
    #  RFE subset only ;models.n= 5; min.RMSE.fit=0.06040702; err.abs.fit.sum=9.059088
    #  RFE subset only ;models.n= 9; min.RMSE.fit=0.05933167; err.abs.fit.sum=8.7421288
    #  RFE subset only ;models.n=15; min.RMSE.fit=0.0584607; err.abs.fit.sum=8.5902066
    #  RFE subset only ;models.n=17; min.RMSE.fit=0.05496899; err.abs.fit.sum=8.0170431
    #  RFE subset only ;models.n=18; min.RMSE.fit=0.05441577; err.abs.fit.sum=7.837223
    #  RFE subset only ;models.n=16; min.RMSE.fit=0.05441577; err.abs.fit.sum=7.837223
    ### bid0_sp
    ### bid1_sp
    # "auto"; err.abs.fit.sum=76.699774; min.RMSE.fit=0.2186429
    # "RFE.X.*"; err.abs.fit.sum=; min.RMSE.fit=0.221114
    ### bid1_sp

    indepVar <- paste(mygetPredictIds(glb_rsp_var)$value, glb_mdl_ensemble, sep = "")
    if (glb_is_classification)
        indepVar <- paste(indepVar, ".prob", sep = "")
    # Some models in glb_mdl_ensemble might not be fitted e.g. RFE.X.Interact
    indepVar <- intersect(indepVar, names(glbObsFit))
    
#     indepVar <- grep(mygetPredictIds(glb_rsp_var)$value, names(glbObsFit), fixed=TRUE, value=TRUE)
#     if (glb_is_regression)
#         indepVar <- indepVar[!grepl("(err\\.abs|accurate)$", indepVar)]
#     if (glb_is_classification && glb_is_binomial)
#         indepVar <- grep("prob$", indepVar, value=TRUE) else
#         indepVar <- indepVar[!grepl("err$", indepVar)]

    #rfe_fit_ens_results <- myrun_rfe(glbObsFit, indepVar)
    
    for (method in c("glm", "glmnet")) {
        for (trainControlMethod in 
             c("boot", "boot632", "cv", "repeatedcv"
               #, "LOOCV" # tuneLength * nrow(fitDF)
               , "LGOCV", "adaptive_cv"
               #, "adaptive_boot"  #error: adaptive$min should be less than 3 
               #, "adaptive_LGOCV" #error: adaptive$min should be less than 3 
               )) {
            #sav_models_df <- glb_models_df; all.equal(sav_models_df, glb_models_df)
            #glb_models_df <- sav_models_df; print(glb_models_df$id)
                
            if ((method == "glm") && (trainControlMethod != "repeatedcv"))
                # glm used only to identify outliers
                next
            
            ret_lst <- myfit_mdl(
                mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
                    id.prefix = paste0(mdl_id_pfx, ".", trainControlMethod), 
                    type = glb_model_type, tune.df = NULL,
                    trainControl.method = trainControlMethod,
                    trainControl.number = glb_rcv_n_folds,
                    trainControl.repeats = glb_rcv_n_repeats,
                    trainControl.classProbs = glb_is_classification,
                    trainControl.summaryFunction = glbMdlMetricSummaryFn,
                    train.metric = glbMdlMetricSummary, 
                    train.maximize = glbMdlMetricMaximize,    
                    train.method = method)),
                indepVar = indepVar, rsp_var = glb_rsp_var, 
                fit_df = glbObsFit, OOB_df = glbObsOOB)
        }
    }
    dsp_models_df <- get_dsp_models_df()
}

if (is.null(glb_sel_mdl_id)) 
    glb_sel_mdl_id <- dsp_models_df[1, "id"] else 
    print(sprintf("User specified selection: %s", glb_sel_mdl_id))   
## [1] "User specified selection: All.X##rcv#glmnet"
myprint_mdl(glb_sel_mdl <- glb_models_lst[[glb_sel_mdl_id]])

##             Length Class      Mode     
## a0            84   -none-     numeric  
## beta        1176   dgCMatrix  S4       
## df            84   -none-     numeric  
## dim            2   -none-     numeric  
## lambda        84   -none-     numeric  
## dev.ratio     84   -none-     numeric  
## nulldev        1   -none-     numeric  
## npasses        1   -none-     numeric  
## jerr           1   -none-     numeric  
## offset         1   -none-     logical  
## call           5   -none-     call     
## nobs           1   -none-     numeric  
## lambdaOpt      1   -none-     numeric  
## xNames        14   -none-     character
## problemType    1   -none-     character
## tuneValue      2   data.frame list     
## obsLevels      1   -none-     logical  
## [1] "min lambda > lambdaOpt:"
##                      (Intercept)                             .pos 
##                     76.694860465                     -0.003728450 
##                           .pos.y                           .rnorm 
##                     -0.003378871                      0.075193372 
##        CellularSubscribers.nonNA                   ChildMortality 
##                      0.006853132                     -0.168446647 
##              FertilityRate.nonNA                           Over60 
##                      1.339044581                      0.185942891 
##                Region.fctrAfrica              Region.fctrAmericas 
##                     -1.777056431                      2.148315203 
## Region.fctrEastern Mediterranean       Region.fctrSouth-East Asia 
##                      1.868369727                      0.709017555 
##       Region.fctrWestern Pacific                          Under15 
##                      1.469834756                     -0.241038585 
## [1] "max lambda < lambdaOpt:"
##                      (Intercept)                             .pos 
##                     7.672078e+01                    -3.745903e-03 
##                           .pos.y                           .rnorm 
##                    -3.390183e-03                     7.483258e-02 
##        CellularSubscribers.nonNA                   ChildMortality 
##                     6.838089e-03                    -1.688486e-01 
##              FertilityRate.nonNA                           Over60 
##                     1.373235e+00                     1.855136e-01 
##                       Population                Region.fctrAfrica 
##                    -6.290707e-09                    -1.763052e+00 
##              Region.fctrAmericas Region.fctrEastern Mediterranean 
##                     2.172714e+00                     1.882474e+00 
##       Region.fctrSouth-East Asia       Region.fctrWestern Pacific 
##                     7.393625e-01                     1.490571e+00 
##                          Under15 
##                    -2.450473e-01
## [1] TRUE
# From here to save(), this should all be in one function
#   these are executed in the same seq twice more:
#       fit.data.training & predict.data.new chunks
print(sprintf("%s fit prediction diagnostics:", glb_sel_mdl_id))
## [1] "All.X##rcv#glmnet fit prediction diagnostics:"
glbObsFit <- glb_get_predictions(df = glbObsFit, mdl_id = glb_sel_mdl_id, 
                                 rsp_var = glb_rsp_var)
print(sprintf("%s OOB prediction diagnostics:", glb_sel_mdl_id))
## [1] "All.X##rcv#glmnet OOB prediction diagnostics:"
glbObsOOB <- glb_get_predictions(df = glbObsOOB, mdl_id = glb_sel_mdl_id, 
                                     rsp_var = glb_rsp_var)

print(glb_featsimp_df <- myget_feats_importance(mdl = glb_sel_mdl, featsimp_df = NULL))
##                                  All.X..rcv.glmnet.imp         imp
## Region.fctrAmericas                        100.0000000 100.0000000
## Region.fctrEastern Mediterranean            86.7582580  86.7582580
## Region.fctrAfrica                           81.7056463  81.7056463
## Region.fctrWestern Pacific                  68.5378200  68.5378200
## FertilityRate.nonNA                         62.8924472  62.8924472
## Region.fctrSouth-East Asia                  33.6639577  33.6639577
## Under15                                     11.2575563  11.2575563
## Over60                                       8.5799966   8.5799966
## ChildMortality                               7.7960960   7.7960960
## .rnorm                                       3.4641145   3.4641145
## CellularSubscribers.nonNA                    0.3162482   0.3162482
## .pos                                         0.1728146   0.1728146
## .pos.y                                       0.1564780   0.1564780
## Population                                   0.0000000   0.0000000
#mdl_id <-"RFE.X.glmnet"; glb_featsimp_df <- myget_feats_importance(glb_models_lst[[mdl_id]], glb_featsimp_df); glb_featsimp_df[, paste0(mdl_id, ".imp")] <- glb_featsimp_df$imp; print(glb_featsimp_df)
#print(head(sbst_featsimp_df <- subset(glb_featsimp_df, is.na(RFE.X.glmnet.imp) | (abs(RFE.X.YeoJohnson.glmnet.imp - RFE.X.glmnet.imp) > 0.0001), select=-imp)))
#print(orderBy(~ -cor.y.abs, subset(glb_feats_df, id %in% c(row.names(sbst_featsimp_df), "startprice.dcm1.is9", "D.weight.post.stop.sum"))))

# Used again in fit.data.training & predict.data.new chunks
glb_analytics_diag_plots <- function(obs_df, mdl_id, prob_threshold=NULL) {
    if (!is.null(featsimp_df <- glb_featsimp_df)) {
        featsimp_df$feat <- gsub("`(.*?)`", "\\1", row.names(featsimp_df))    
        featsimp_df$feat.interact <- gsub("(.*?):(.*)", "\\2", featsimp_df$feat)
        featsimp_df$feat <- gsub("(.*?):(.*)", "\\1", featsimp_df$feat)    
        featsimp_df$feat.interact <- 
            ifelse(featsimp_df$feat.interact == featsimp_df$feat, 
                                            NA, featsimp_df$feat.interact)
        featsimp_df$feat <- 
            gsub("(.*?)\\.fctr(.*)", "\\1\\.fctr", featsimp_df$feat)
        featsimp_df$feat.interact <- 
            gsub("(.*?)\\.fctr(.*)", "\\1\\.fctr", featsimp_df$feat.interact) 
        featsimp_df <- orderBy(~ -imp.max, 
            summaryBy(imp ~ feat + feat.interact, data=featsimp_df,
                      FUN=max))    
        #rex_str=":(.*)"; txt_vctr=tail(featsimp_df$feat); ret_lst <- regexec(rex_str, txt_vctr); ret_lst <- regmatches(txt_vctr, ret_lst); ret_vctr <- sapply(1:length(ret_lst), function(pos_ix) ifelse(length(ret_lst[[pos_ix]]) > 0, ret_lst[[pos_ix]], "")); print(ret_vctr <- ret_vctr[ret_vctr != ""])    
        
        featsimp_df <- subset(featsimp_df, !is.na(imp.max))
        if (nrow(featsimp_df) > 5) {
            warning("Limiting important feature scatter plots to 5 out of ",
                    nrow(featsimp_df))
            featsimp_df <- head(featsimp_df, 5)
        }
        
    #     if (!all(is.na(featsimp_df$feat.interact)))
    #         stop("not implemented yet")
        rsp_var_out <- mygetPredictIds(glb_rsp_var, mdl_id)$value
        for (var in featsimp_df$feat) {
            plot_df <- melt(obs_df, id.vars = var, 
                            measure.vars = c(glb_rsp_var, rsp_var_out))
    
            print(myplot_scatter(plot_df, var, "value", colorcol_name = "variable",
                                facet_colcol_name = "variable", jitter = TRUE) + 
                          guides(color = FALSE))
        }
    }
    
    if (glb_is_regression) {
        if (is.null(featsimp_df) || (nrow(featsimp_df) == 0))
            warning("No important features in glb_fin_mdl") else
            print(myplot_prediction_regression(df=obs_df, 
                        feat_x=ifelse(nrow(featsimp_df) > 1, featsimp_df$feat[2],
                                      ".rownames"), 
                                               feat_y=featsimp_df$feat[1],
                        rsp_var=glb_rsp_var, rsp_var_out=rsp_var_out,
                        id_vars=glbFeatsId)
    #               + facet_wrap(reformulate(featsimp_df$feat[2])) # if [1 or 2] is a factor
    #               + geom_point(aes_string(color="<col_name>.fctr")) #  to color the plot
                  )
    }    
    
    if (glb_is_classification) {
        if (is.null(featsimp_df) || (nrow(featsimp_df) == 0))
            warning("No features in selected model are statistically important")
        else print(myplot_prediction_classification(df = obs_df, 
                                feat_x = ifelse(nrow(featsimp_df) > 1, 
                                                featsimp_df$feat[2], ".rownames"),
                                               feat_y = featsimp_df$feat[1],
                                                rsp_var = glb_rsp_var, 
                                                rsp_var_out = rsp_var_out, 
                                                id_vars = glbFeatsId,
                                                prob_threshold = prob_threshold))
    }    
}

if (glb_is_classification && glb_is_binomial)
    glb_analytics_diag_plots(obs_df = glbObsOOB, mdl_id = glb_sel_mdl_id, 
            prob_threshold = glb_models_df[glb_models_df$id == glb_sel_mdl_id, 
                                           "opt.prob.threshold.OOB"]) else
    glb_analytics_diag_plots(obs_df = glbObsOOB, mdl_id = glb_sel_mdl_id)                  
## Warning in glb_analytics_diag_plots(obs_df = glbObsOOB, mdl_id =
## glb_sel_mdl_id): Limiting important feature scatter plots to 5 out of 10

##              Country                Region Population Under15 Over60
## 348     Sierra Leone                Africa       5979   41.74   4.41
## 292            Libya Eastern Mediterranean       6155   29.45   6.96
## 323         Pakistan Eastern Mediterranean     179000   34.31   6.44
## 301 Marshall Islands       Western Pacific         53   30.10   8.84
## 199           Angola                Africa      20821   47.58   3.84
##     FertilityRate LifeExpectancy ChildMortality CellularSubscribers
## 348          4.86             47          181.6               35.63
## 292          2.47             65           15.4              155.70
## 323          3.35             67           85.9               61.61
## 301            NA             60           37.9                  NA
## 199          6.10             51          163.5               48.38
##     LiteracyRate  GNI PrimarySchoolEnrollmentMale
## 348         42.1  840                          NA
## 292         89.2   NA                          NA
## 323           NA 2870                        81.3
## 301           NA   NA                          NA
## 199         70.1 5230                        93.1
##     PrimarySchoolEnrollmentFemale .src     .rnorm .pos .pos.y .category
## 348                            NA Test -0.4454942  348    348    .dummy
## 292                            NA Test -0.4230342  292    292    .dummy
## 323                          66.5 Test  1.5716339  323    323    .dummy
## 301                            NA Test -1.2500570  301    301    .dummy
## 199                          78.2 Test  0.7809128  199    199    .dummy
##         Country.fctr           Region.fctr FertilityRate.nonNA
## 348     Sierra Leone                Africa                4.86
## 292            Libya Eastern Mediterranean                2.47
## 323         Pakistan Eastern Mediterranean                3.35
## 301 Marshall Islands       Western Pacific                2.38
## 199           Angola                Africa                6.10
##     CellularSubscribers.nonNA LifeExpectancy.All.X..rcv.glmnet
## 348                     35.63                         39.30220
## 292                    155.70                         72.42347
## 323                     61.61                         59.73100
## 301                     21.63                         67.25795
## 199                     48.38                         43.75571
##     LifeExpectancy.All.X..rcv.glmnet.err
## 348                             7.697800
## 292                             7.423472
## 323                             7.268996
## 301                             7.257954
## 199                             7.244292
##     LifeExpectancy.All.X..rcv.glmnet.err.abs
## 348                                 7.697800
## 292                                 7.423472
## 323                                 7.268996
## 301                                 7.257954
## 199                                 7.244292
##     LifeExpectancy.All.X..rcv.glmnet.is.acc           .label
## 348                                   FALSE     Sierra Leone
## 292                                   FALSE            Libya
## 323                                   FALSE         Pakistan
## 301                                   FALSE Marshall Islands
## 199                                   FALSE           Angola

if (!is.null(glbFeatsCategory)) {
    glbLvlCategory <- merge(glbLvlCategory, 
            myget_category_stats(obs_df = glbObsFit, mdl_id = glb_sel_mdl_id, 
                                 label = "fit"), 
                            by = glbFeatsCategory, all = TRUE)
    row.names(glbLvlCategory) <- glbLvlCategory[, glbFeatsCategory]
    glbLvlCategory <- merge(glbLvlCategory, 
            myget_category_stats(obs_df = glbObsOOB, mdl_id = glb_sel_mdl_id,
                                 label="OOB"),
                          #by=glbFeatsCategory, all=TRUE) glb_ctgry-df already contains .n.OOB ?
                          all = TRUE)
    row.names(glbLvlCategory) <- glbLvlCategory[, glbFeatsCategory]
    if (any(grepl("OOB", glbMdlMetricsEval)))
        print(orderBy(~-err.abs.OOB.mean, glbLvlCategory)) else
            print(orderBy(~-err.abs.fit.mean, glbLvlCategory))
    print(colSums(glbLvlCategory[, -grep(glbFeatsCategory, names(glbLvlCategory))]))
}
##        .category .n.OOB .n.Fit .n.Tst .freqRatio.Fit .freqRatio.OOB
## .dummy    .dummy    194    194    194              1              1
##        .freqRatio.Tst err.abs.fit.sum err.abs.fit.mean .n.fit
## .dummy              1        447.8162         2.308331    194
##        err.abs.OOB.sum err.abs.OOB.mean
## .dummy        508.7739         2.622546
##           .n.OOB           .n.Fit           .n.Tst   .freqRatio.Fit 
##       194.000000       194.000000       194.000000         1.000000 
##   .freqRatio.OOB   .freqRatio.Tst  err.abs.fit.sum err.abs.fit.mean 
##         1.000000         1.000000       447.816227         2.308331 
##           .n.fit  err.abs.OOB.sum err.abs.OOB.mean 
##       194.000000       508.773944         2.622546
write.csv(glbObsOOB[, c(glbFeatsId, 
                grep(glb_rsp_var, names(glbObsOOB), fixed=TRUE, value=TRUE))], 
    paste0(gsub(".", "_", paste0(glbOut$pfx, glb_sel_mdl_id), fixed=TRUE), 
           "_OOBobs.csv"), row.names=FALSE)

fit.models_2_chunk_df <- 
    myadd_chunk(NULL, "fit.models_2_bgn", label.minor = "teardown")
##              label step_major step_minor label_minor    bgn end elapsed
## 1 fit.models_2_bgn          1          0    teardown 47.747  NA      NA
glb_chunks_df <- myadd_chunk(glb_chunks_df, "fit.models", major.inc=FALSE)
##         label step_major step_minor label_minor    bgn    end elapsed
## 18 fit.models          8          2           2 40.087 47.755   7.669
## 19 fit.models          8          3           3 47.756     NA      NA
# if (sum(is.na(glbObsAll$D.P.http)) > 0)
#         stop("fit.models_3: Why is this happening ?")

#stop(here"); glb2Sav()
sync_glb_obs_df <- function() {
    # Merge or cbind ?
    for (col in setdiff(names(glbObsFit), names(glbObsTrn)))
        glbObsTrn[glbObsTrn$.lcn == "Fit", col] <<- glbObsFit[, col]
    for (col in setdiff(names(glbObsFit), names(glbObsAll)))
        glbObsAll[glbObsAll$.lcn == "Fit", col] <<- glbObsFit[, col]
    if (all(is.na(glbObsNew[, glb_rsp_var])))
        for (col in setdiff(names(glbObsOOB), names(glbObsTrn)))
            glbObsTrn[glbObsTrn$.lcn == "OOB", col] <<- glbObsOOB[, col]
    for (col in setdiff(names(glbObsOOB), names(glbObsAll)))
        glbObsAll[glbObsAll$.lcn == "OOB", col] <<- glbObsOOB[, col]
}
sync_glb_obs_df()
    
print(setdiff(names(glbObsNew), names(glbObsAll)))
## character(0)
replay.petrisim(pn=glb_analytics_pn, 
    replay.trans=(glb_analytics_avl_objs <- c(glb_analytics_avl_objs, 
        "model.selected")), flip_coord=TRUE)
## time trans    "bgn " "fit.data.training.all " "predict.data.new " "end " 
## 0.0000   multiple enabled transitions:  data.training.all data.new model.selected    firing:  data.training.all 
## 1.0000    1   2 1 0 0 
## 1.0000   multiple enabled transitions:  data.training.all data.new model.selected model.final data.training.all.prediction   firing:  data.new 
## 2.0000    2   1 1 1 0 
## 2.0000   multiple enabled transitions:  data.training.all data.new model.selected model.final data.training.all.prediction data.new.prediction   firing:  model.selected 
## 3.0000    3   0 2 1 0

glb_chunks_df <- myadd_chunk(glb_chunks_df, "fit.data.training", major.inc = TRUE)
##                label step_major step_minor label_minor    bgn    end
## 19        fit.models          8          3           3 47.756 51.444
## 20 fit.data.training          9          0           0 51.445     NA
##    elapsed
## 19   3.688
## 20      NA

Step 9.0: fit data training

#load(paste0(glb_inp_pfx, "dsk.RData"))

if (!is.null(glb_fin_mdl_id) && (glb_fin_mdl_id %in% names(glb_models_lst))) {
    warning("Final model same as user selected model")
    glb_fin_mdl <- glb_models_lst[[glb_fin_mdl_id]]
} else 
# if (nrow(glbObsFit) + length(glbObsFitOutliers) == nrow(glbObsTrn))
if (!all(is.na(glbObsNew[, glb_rsp_var])))
{    
    warning("Final model same as glb_sel_mdl_id")
    glb_fin_mdl_id <- paste0("Final.", glb_sel_mdl_id)
    glb_fin_mdl <- glb_sel_mdl
    glb_models_lst[[glb_fin_mdl_id]] <- glb_fin_mdl
} else {    
            if (grepl("RFE\\.X", names(glbMdlFamilies))) {
                indepVar <- mygetIndepVar(glb_feats_df)
                rfe_trn_results <- 
                    myrun_rfe(glbObsTrn, indepVar, glbRFESizes[["Final"]])
                if (!isTRUE(all.equal(sort(predictors(rfe_trn_results)),
                                      sort(predictors(rfe_fit_results))))) {
                    print("Diffs predictors(rfe_trn_results) vs. predictors(rfe_fit_results):")
                    print(setdiff(predictors(rfe_trn_results), predictors(rfe_fit_results)))
                    print("Diffs predictors(rfe_fit_results) vs. predictors(rfe_trn_results):")
                    print(setdiff(predictors(rfe_fit_results), predictors(rfe_trn_results)))
            }
        }
    # }    

    if (grepl("Ensemble", glb_sel_mdl_id)) {
        # Find which models are relevant
        mdlimp_df <- subset(myget_feats_importance(glb_sel_mdl), imp > 5)
        # Fit selected models on glbObsTrn
        for (mdl_id in gsub(".prob", "", 
gsub(mygetPredictIds(glb_rsp_var)$value, "", row.names(mdlimp_df), fixed = TRUE),
                            fixed = TRUE)) {
            mdl_id_components <- unlist(strsplit(mdl_id, "[.]"))
            mdlIdPfx <- paste0(c(head(mdl_id_components, -1), "Train"), 
                               collapse = ".")
            if (grepl("RFE\\.X\\.", mdlIdPfx)) 
                mdlIndepVars <- myadjustInteractionFeats(glb_feats_df, myextract_actual_feats(
                    predictors(rfe_trn_results))) else
                mdlIndepVars <- trim(unlist(
            strsplit(glb_models_df[glb_models_df$id == mdl_id, "feats"], "[,]")))
            ret_lst <- 
                myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
                        id.prefix = mdlIdPfx, 
                        type = glb_model_type, tune.df = glbMdlTuneParams,
                        trainControl.method = "repeatedcv",
                        trainControl.number = glb_rcv_n_folds,
                        trainControl.repeats = glb_rcv_n_repeats,
                        trainControl.classProbs = glb_is_classification,
                        trainControl.summaryFunction = glbMdlMetricSummaryFn,
                        train.metric = glbMdlMetricSummary, 
                        train.maximize = glbMdlMetricMaximize,    
                        train.method = tail(mdl_id_components, 1))),
                    indepVar = mdlIndepVars,
                    rsp_var = glb_rsp_var, 
                    fit_df = glbObsTrn, OOB_df = NULL)
            
            glbObsTrn <- glb_get_predictions(df = glbObsTrn,
                                                mdl_id = tail(glb_models_df$id, 1), 
                                                rsp_var = glb_rsp_var,
                                                prob_threshold_def = 
                    subset(glb_models_df, id == mdl_id)$opt.prob.threshold.OOB)
            glbObsNew <- glb_get_predictions(df = glbObsNew,
                                                mdl_id = tail(glb_models_df$id, 1), 
                                                rsp_var = glb_rsp_var,
                                                prob_threshold_def = 
                    subset(glb_models_df, id == mdl_id)$opt.prob.threshold.OOB)
        }    
    }
    
    # "Final" model
    if ((model_method <- glb_sel_mdl$method) == "custom")
        # get actual method from the mdl_id
        model_method <- tail(unlist(strsplit(glb_sel_mdl_id, "[.]")), 1)
        
    if (grepl("Ensemble", glb_sel_mdl_id)) {
        # Find which models are relevant
        mdlimp_df <- subset(myget_feats_importance(glb_sel_mdl), imp > 5)
        if (glb_is_classification && glb_is_binomial)
            indepVar <- gsub("(.*)\\.(.*)\\.prob", "\\1\\.Train\\.\\2\\.prob",
                                    row.names(mdlimp_df)) else
            indepVar <- gsub("(.*)\\.(.*)", "\\1\\.Train\\.\\2",
                                    row.names(mdlimp_df))
    } else 
    if (grepl("RFE.X", glb_sel_mdl_id, fixed = TRUE)) {
        indepVar <- myextract_actual_feats(predictors(rfe_trn_results))
    } else indepVar <- 
                trim(unlist(strsplit(glb_models_df[glb_models_df$id ==
                                                   glb_sel_mdl_id
                                                   , "feats"], "[,]")))
        
    if (!is.null(glb_preproc_methods) &&
        ((match_pos <- regexpr(gsub(".", "\\.", 
                                    paste(glb_preproc_methods, collapse = "|"),
                                   fixed = TRUE), glb_sel_mdl_id)) != -1))
        ths_preProcess <- str_sub(glb_sel_mdl_id, match_pos, 
                                match_pos + attr(match_pos, "match.length") - 1) else
        ths_preProcess <- NULL                                      

    mdl_id_pfx <- ifelse(grepl("Ensemble", glb_sel_mdl_id),
                                   "Final.Ensemble", "Final")
    
    trnobs_df <- glbObsTrn 
    if (!is.null(glbObsTrnOutliers[[mdl_id_pfx]])) {
        trnobs_df <- glbObsTrn[!(glbObsTrn[, glbFeatsId] %in% glbObsTrnOutliers[[mdl_id_pfx]]), ]
        print(sprintf("Outliers removed: %d", nrow(glbObsTrn) - nrow(trnobs_df)))
        print(setdiff(glbObsTrn[, glbFeatsId], trnobs_df[, glbFeatsId]))
    }    
        
    # Force fitting of Final.glm to identify outliers
    method_vctr <- unique(c(myparseMdlId(glb_sel_mdl_id)$alg, glbMdlFamilies[["Final"]]))
    for (method in method_vctr) {
        #source("caret_nominalTrainWorkflow.R")
        
        # glmnet requires at least 2 indep vars
        if ((length(indepVar) == 1) && (method %in% "glmnet"))
            next
        
        ret_lst <- 
            myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
                    id.prefix = mdl_id_pfx, 
                    type = glb_model_type, trainControl.method = "repeatedcv",
                    trainControl.number = glb_rcv_n_folds, 
                    trainControl.repeats = glb_rcv_n_repeats,
                    trainControl.classProbs = glb_is_classification,
                    trainControl.summaryFunction = glbMdlMetricSummaryFn,
                    trainControl.allowParallel = glbMdlAllowParallel,
                    train.metric = glbMdlMetricSummary, 
                    train.maximize = glbMdlMetricMaximize,    
                    train.method = method,
                    train.preProcess = ths_preProcess)),
                indepVar = indepVar, rsp_var = glb_rsp_var, 
                fit_df = trnobs_df, OOB_df = NULL)
        
        if ((length(method_vctr) == 1) || (method != "glm")) {
            glb_fin_mdl <- glb_models_lst[[length(glb_models_lst)]] 
            glb_fin_mdl_id <- glb_models_df[length(glb_models_lst), "id"]
        }
    }
        
}
## Warning: Final model same as glb_sel_mdl_id
rm(ret_lst)
## Warning in rm(ret_lst): object 'ret_lst' not found
glb_chunks_df <- myadd_chunk(glb_chunks_df, "fit.data.training", major.inc=FALSE)
##                label step_major step_minor label_minor    bgn    end
## 20 fit.data.training          9          0           0 51.445 51.873
## 21 fit.data.training          9          1           1 51.874     NA
##    elapsed
## 20   0.428
## 21      NA
#stop(here"); glb2Sav()
if (glb_is_classification && glb_is_binomial) 
    prob_threshold <- glb_models_df[glb_models_df$id == glb_sel_mdl_id,
                                        "opt.prob.threshold.OOB"] else 
    prob_threshold <- NULL

if (grepl("Ensemble", glb_fin_mdl_id)) {
    # Get predictions for each model in ensemble; Outliers that have been moved to OOB might not have been predicted yet
    mdlEnsembleComps <- unlist(str_split(subset(glb_models_df, 
                                                id == glb_fin_mdl_id)$feats, ","))
    if (glb_is_classification && glb_is_binomial)
        mdlEnsembleComps <- gsub("\\.prob$", "", mdlEnsembleComps)
    mdlEnsembleComps <- gsub(paste0("^", 
                        gsub(".", "\\.", mygetPredictIds(glb_rsp_var)$value, fixed = TRUE)),
                             "", mdlEnsembleComps)
    for (mdl_id in mdlEnsembleComps) {
        glbObsTrn <- glb_get_predictions(df = glbObsTrn, mdl_id = mdl_id, 
                                            rsp_var = glb_rsp_var,
                                            prob_threshold_def = prob_threshold)
        glbObsNew <- glb_get_predictions(df = glbObsNew, mdl_id = mdl_id, 
                                            rsp_var = glb_rsp_var,
                                            prob_threshold_def = prob_threshold)
    }    
}
glbObsTrn <- glb_get_predictions(df = glbObsTrn, mdl_id = glb_fin_mdl_id, 
                                     rsp_var = glb_rsp_var,
                                    prob_threshold_def = prob_threshold)

glb_featsimp_df <- myget_feats_importance(mdl=glb_fin_mdl,
                                          featsimp_df=glb_featsimp_df)
#glb_featsimp_df[, paste0(glb_fin_mdl_id, ".imp")] <- glb_featsimp_df$imp
print(glb_featsimp_df)
##                                  All.X..rcv.glmnet.imp         imp
## Region.fctrAmericas                        100.0000000 100.0000000
## Region.fctrEastern Mediterranean            86.7582580  86.7582580
## Region.fctrAfrica                           81.7056463  81.7056463
## Region.fctrWestern Pacific                  68.5378200  68.5378200
## FertilityRate.nonNA                         62.8924472  62.8924472
## Region.fctrSouth-East Asia                  33.6639577  33.6639577
## Under15                                     11.2575563  11.2575563
## Over60                                       8.5799966   8.5799966
## ChildMortality                               7.7960960   7.7960960
## .rnorm                                       3.4641145   3.4641145
## CellularSubscribers.nonNA                    0.3162482   0.3162482
## .pos                                         0.1728146   0.1728146
## .pos.y                                       0.1564780   0.1564780
## Population                                   0.0000000   0.0000000
if (glb_is_classification && glb_is_binomial)
    glb_analytics_diag_plots(obs_df=glbObsTrn, mdl_id=glb_fin_mdl_id, 
            prob_threshold=glb_models_df[glb_models_df$id == glb_sel_mdl_id, 
                                         "opt.prob.threshold.OOB"]) else
    glb_analytics_diag_plots(obs_df=glbObsTrn, mdl_id=glb_fin_mdl_id)                  
## Warning in glb_analytics_diag_plots(obs_df = glbObsTrn, mdl_id =
## glb_fin_mdl_id): Limiting important feature scatter plots to 5 out of 10

##                Country                Region Population Under15 Over60
## 98               Libya Eastern Mediterranean       6155   29.45   6.96
## 107   Marshall Islands       Western Pacific         53   30.10   8.84
## 142 Russian Federation                Europe     143000   15.45  18.60
## 16             Belarus                Europe       9405   15.10  19.31
## 166          Swaziland                Africa       1231   38.05   5.34
##     FertilityRate LifeExpectancy ChildMortality CellularSubscribers
## 98           2.47             65           15.4              155.70
## 107            NA             60           37.9                  NA
## 142          1.51             69           10.3              179.31
## 16           1.47             71            5.2              111.88
## 166          3.48             50           79.7               63.70
##     LiteracyRate   GNI PrimarySchoolEnrollmentMale
## 98          89.2    NA                          NA
## 107           NA    NA                          NA
## 142         99.6 20560                          NA
## 16            NA 14460                          NA
## 166         87.4  5930                          NA
##     PrimarySchoolEnrollmentFemale  .src     .rnorm .pos .pos.y
## 98                             NA Train  0.2326315   98     98
## 107                            NA Train -0.4578521  107    107
## 142                            NA Train -0.7327977  142    142
## 16                             NA Train  0.2941850   16     16
## 166                            NA Train -0.3689090  166    166
##           Country.fctr           Region.fctr FertilityRate.nonNA
## 98               Libya Eastern Mediterranean                2.47
## 107   Marshall Islands       Western Pacific                2.47
## 142 Russian Federation                Europe                1.51
## 16             Belarus                Europe                1.47
## 166          Swaziland                Africa                3.48
##     CellularSubscribers.nonNA .lcn .category
## 98                     155.70  OOB    .dummy
## 107                     21.63  OOB    .dummy
## 142                    179.31  OOB    .dummy
## 16                     111.88  OOB    .dummy
## 166                     63.70  OOB    .dummy
##     LifeExpectancy.All.X..rcv.glmnet LifeExpectancy.All.X..rcv.glmnet.err
## 98                                NA                                   NA
## 107                               NA                                   NA
## 142                               NA                                   NA
## 16                                NA                                   NA
## 166                               NA                                   NA
##     LifeExpectancy.All.X..rcv.glmnet.err.abs
## 98                                        NA
## 107                                       NA
## 142                                       NA
## 16                                        NA
## 166                                       NA
##     LifeExpectancy.All.X..rcv.glmnet.is.acc
## 98                                       NA
## 107                                      NA
## 142                                      NA
## 16                                       NA
## 166                                      NA
##     LifeExpectancy.Final.All.X..rcv.glmnet
## 98                                73.85502
## 107                               68.82223
## 142                               76.87829
## 16                                78.41524
## 166                               57.18137
##     LifeExpectancy.Final.All.X..rcv.glmnet.err
## 98                                    8.855020
## 107                                   8.822225
## 142                                   7.878286
## 16                                    7.415240
## 166                                   7.181373
##     LifeExpectancy.Final.All.X..rcv.glmnet.err.abs
## 98                                        8.855020
## 107                                       8.822225
## 142                                       7.878286
## 16                                        7.415240
## 166                                       7.181373
##     LifeExpectancy.Final.All.X..rcv.glmnet.is.acc             .label
## 98                                          FALSE              Libya
## 107                                         FALSE   Marshall Islands
## 142                                         FALSE Russian Federation
## 16                                          FALSE            Belarus
## 166                                         FALSE          Swaziland

dsp_feats_vctr <- c(NULL)
for(var in grep(".imp", names(glb_feats_df), fixed=TRUE, value=TRUE))
    dsp_feats_vctr <- union(dsp_feats_vctr, 
                            glb_feats_df[!is.na(glb_feats_df[, var]), "id"])

# print(glbObsTrn[glbObsTrn$UniqueID %in% FN_OOB_ids, 
#                     grep(glb_rsp_var, names(glbObsTrn), value=TRUE)])

print(setdiff(names(glbObsTrn), names(glbObsAll)))
## [1] "LifeExpectancy.Final.All.X..rcv.glmnet"        
## [2] "LifeExpectancy.Final.All.X..rcv.glmnet.err"    
## [3] "LifeExpectancy.Final.All.X..rcv.glmnet.err.abs"
## [4] "LifeExpectancy.Final.All.X..rcv.glmnet.is.acc"
for (col in setdiff(names(glbObsTrn), names(glbObsAll)))
    # Merge or cbind ?
    glbObsAll[glbObsAll$.src == "Train", col] <- glbObsTrn[, col]

print(setdiff(names(glbObsFit), names(glbObsAll)))
## character(0)
print(setdiff(names(glbObsOOB), names(glbObsAll)))
## character(0)
for (col in setdiff(names(glbObsOOB), names(glbObsAll)))
    # Merge or cbind ?
    glbObsAll[glbObsAll$.lcn == "OOB", col] <- glbObsOOB[, col]
    
print(setdiff(names(glbObsNew), names(glbObsAll)))
## character(0)
#glb2Sav(); all.equal(savObsAll, glbObsAll); all.equal(sav_models_lst, glb_models_lst)
#load(file = paste0(glbOut$pfx, "dsk_knitr.RData"))
#cmpCols <- names(glbObsAll)[!grepl("\\.Final\\.", names(glbObsAll))]; all.equal(savObsAll[, cmpCols], glbObsAll[, cmpCols]); all.equal(savObsAll[, "H.P.http"], glbObsAll[, "H.P.http"]); 

replay.petrisim(pn = glb_analytics_pn, 
    replay.trans = (glb_analytics_avl_objs <- c(glb_analytics_avl_objs, 
        "data.training.all.prediction","model.final")), flip_coord = TRUE)
## time trans    "bgn " "fit.data.training.all " "predict.data.new " "end " 
## 0.0000   multiple enabled transitions:  data.training.all data.new model.selected    firing:  data.training.all 
## 1.0000    1   2 1 0 0 
## 1.0000   multiple enabled transitions:  data.training.all data.new model.selected model.final data.training.all.prediction   firing:  data.new 
## 2.0000    2   1 1 1 0 
## 2.0000   multiple enabled transitions:  data.training.all data.new model.selected model.final data.training.all.prediction data.new.prediction   firing:  model.selected 
## 3.0000    3   0 2 1 0 
## 3.0000   multiple enabled transitions:  model.final data.training.all.prediction data.new.prediction     firing:  data.training.all.prediction 
## 4.0000    5   0 1 1 1 
## 4.0000   multiple enabled transitions:  model.final data.training.all.prediction data.new.prediction     firing:  model.final 
## 5.0000    4   0 0 2 1

glb_chunks_df <- myadd_chunk(glb_chunks_df, "predict.data.new", major.inc = TRUE)
##                label step_major step_minor label_minor    bgn    end
## 21 fit.data.training          9          1           1 51.874 56.316
## 22  predict.data.new         10          0           0 56.317     NA
##    elapsed
## 21   4.442
## 22      NA

Step 10.0: predict data new

## Warning in glb_analytics_diag_plots(obs_df = glbObsNew, mdl_id =
## glb_fin_mdl_id, : Limiting important feature scatter plots to 5 out of 10

##              Country                Region Population Under15 Over60
## 348     Sierra Leone                Africa       5979   41.74   4.41
## 292            Libya Eastern Mediterranean       6155   29.45   6.96
## 323         Pakistan Eastern Mediterranean     179000   34.31   6.44
## 301 Marshall Islands       Western Pacific         53   30.10   8.84
## 199           Angola                Africa      20821   47.58   3.84
##     FertilityRate LifeExpectancy ChildMortality CellularSubscribers
## 348          4.86             47          181.6               35.63
## 292          2.47             65           15.4              155.70
## 323          3.35             67           85.9               61.61
## 301            NA             60           37.9                  NA
## 199          6.10             51          163.5               48.38
##     LiteracyRate  GNI PrimarySchoolEnrollmentMale
## 348         42.1  840                          NA
## 292         89.2   NA                          NA
## 323           NA 2870                        81.3
## 301           NA   NA                          NA
## 199         70.1 5230                        93.1
##     PrimarySchoolEnrollmentFemale .src     .rnorm .pos .pos.y
## 348                            NA Test -0.4454942  348    348
## 292                            NA Test -0.4230342  292    292
## 323                          66.5 Test  1.5716339  323    323
## 301                            NA Test -1.2500570  301    301
## 199                          78.2 Test  0.7809128  199    199
##         Country.fctr           Region.fctr FertilityRate.nonNA
## 348     Sierra Leone                Africa                4.86
## 292            Libya Eastern Mediterranean                2.47
## 323         Pakistan Eastern Mediterranean                3.35
## 301 Marshall Islands       Western Pacific                2.38
## 199           Angola                Africa                6.10
##     CellularSubscribers.nonNA .lcn .category
## 348                     35.63  OOB    .dummy
## 292                    155.70  OOB    .dummy
## 323                     61.61  OOB    .dummy
## 301                     21.63  OOB    .dummy
## 199                     48.38  OOB    .dummy
##     LifeExpectancy.Final.All.X..rcv.glmnet
## 348                               39.30220
## 292                               72.42347
## 323                               59.73100
## 301                               67.25795
## 199                               43.75571
##     LifeExpectancy.Final.All.X..rcv.glmnet.err
## 348                                   7.697800
## 292                                   7.423472
## 323                                   7.268996
## 301                                   7.257954
## 199                                   7.244292
##     LifeExpectancy.Final.All.X..rcv.glmnet.err.abs
## 348                                       7.697800
## 292                                       7.423472
## 323                                       7.268996
## 301                                       7.257954
## 199                                       7.244292
##     LifeExpectancy.Final.All.X..rcv.glmnet.is.acc           .label
## 348                                         FALSE     Sierra Leone
## 292                                         FALSE            Libya
## 323                                         FALSE         Pakistan
## 301                                         FALSE Marshall Islands
## 199                                         FALSE           Angola

## [1] TRUE
## [1] "glb_sel_mdl_id: All.X##rcv#glmnet"
## [1] "glb_fin_mdl_id: Final.All.X##rcv#glmnet"
## [1] "Cross Validation issues:"
## Max.cor.Y.rcv.1X1###glmnet 
##                          0
##                                 min.RMSE.OOB max.R.sq.OOB max.Adj.R.sq.fit
## Max.cor.Y##rcv#rpart                3.138409    0.8845143               NA
## Low.cor.X##rcv#glmnet               3.221132    0.8783460        0.8920680
## All.X##rcv#glmnet                   3.221132    0.8783460        0.8920680
## All.X##rcv#glm                      3.241612    0.8767941        0.8930342
## Interact.High.cor.Y##rcv#glmnet     3.403945    0.8641454        0.8614748
## Max.cor.Y.rcv.1X1###glmnet          3.488525    0.8573102        0.8550496
##                                 min.RMSE.fit
## Max.cor.Y##rcv#rpart                3.612457
## Low.cor.X##rcv#glmnet               3.175766
## All.X##rcv#glmnet                   3.175766
## All.X##rcv#glm                      3.185692
## Interact.High.cor.Y##rcv#glmnet     3.508182
## Max.cor.Y.rcv.1X1###glmnet          3.497785
## [1] "All.X##rcv#glmnet OOB RMSE: 3.2211"
##        err.abs.fit.sum err.abs.OOB.sum err.abs.trn.sum err.abs.new.sum
## .dummy        447.8162        508.7739        447.8162        508.7739
##        .freqRatio.Fit .freqRatio.OOB .freqRatio.Tst .n.Fit .n.OOB .n.Tst
## .dummy              1              1              1    194    194    194
##        .n.fit .n.new .n.trn err.abs.OOB.mean err.abs.fit.mean
## .dummy    194    194    194         2.622546         2.308331
##        err.abs.new.mean err.abs.trn.mean
## .dummy         2.622546         2.308331
##  err.abs.fit.sum  err.abs.OOB.sum  err.abs.trn.sum  err.abs.new.sum 
##       447.816227       508.773944       447.816227       508.773944 
##   .freqRatio.Fit   .freqRatio.OOB   .freqRatio.Tst           .n.Fit 
##         1.000000         1.000000         1.000000       194.000000 
##           .n.OOB           .n.Tst           .n.fit           .n.new 
##       194.000000       194.000000       194.000000       194.000000 
##           .n.trn err.abs.OOB.mean err.abs.fit.mean err.abs.new.mean 
##       194.000000         2.622546         2.308331         2.622546 
## err.abs.trn.mean 
##         2.308331
## [1] "Final.All.X##rcv#glmnet prediction stats for glbObsNew:"
##                  id max.R.sq.new min.RMSE.new max.Adj.R.sq.new
## 1 All.X##rcv#glmnet     0.878346     3.221132        0.8688312
## [1] "Features Importance for selected models:"
##                                  All.X..rcv.glmnet.imp
## Region.fctrAmericas                          100.00000
## Region.fctrEastern Mediterranean              86.75826
## Region.fctrAfrica                             81.70565
## Region.fctrWestern Pacific                    68.53782
## FertilityRate.nonNA                           62.89245
## Region.fctrSouth-East Asia                    33.66396
## Under15                                       11.25756
## [1] "glbObsNew prediction stats:"
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

##                   label step_major step_minor label_minor    bgn    end
## 22     predict.data.new         10          0           0 56.317 67.441
## 23 display.session.info         11          0           0 67.442     NA
##    elapsed
## 22  11.125
## 23      NA

Null Hypothesis (\(\sf{H_{0}}\)): mpg is not impacted by am_fctr.
The variance by am_fctr appears to be independent. #{r q1, cache=FALSE} # print(t.test(subset(cars_df, am_fctr == "automatic")$mpg, # subset(cars_df, am_fctr == "manual")$mpg, # var.equal=FALSE)$conf) # We reject the null hypothesis i.e. we have evidence to conclude that am_fctr impacts mpg (95% confidence). Manual transmission is better for miles per gallon versus automatic transmission.

##                        label step_major step_minor label_minor    bgn
## 16                fit.models          8          0           0 21.984
## 22          predict.data.new         10          0           0 56.317
## 18                fit.models          8          2           2 40.087
## 2               inspect.data          2          0           0  7.591
## 17                fit.models          8          1           1 33.377
## 21         fit.data.training          9          1           1 51.874
## 19                fit.models          8          3           3 47.756
## 3                 scrub.data          2          1           1 14.998
## 1                import.data          1          0           0  5.756
## 15           select.features          7          0           0 20.412
## 12       manage.missing.data          4          0           0 19.321
## 11      extract.features.end          3          6           6 18.453
## 20         fit.data.training          9          0           0 51.445
## 14   partition.data.training          6          0           0 20.253
## 10   extract.features.string          3          5           5 18.376
## 7     extract.features.image          3          2           2 18.239
## 9      extract.features.text          3          4           4 18.327
## 13              cluster.data          5          0           0 20.206
## 4             transform.data          2          2           2 18.144
## 6  extract.features.datetime          3          1           1 18.204
## 8     extract.features.price          3          3           3 18.291
## 5           extract.features          3          0           0 18.183
##       end elapsed duration
## 16 33.376  11.392   11.392
## 22 67.441  11.125   11.124
## 18 47.755   7.669    7.668
## 2  14.998   7.407    7.407
## 17 40.086   6.709    6.709
## 21 56.316   4.442    4.442
## 19 51.444   3.688    3.688
## 3  18.144   3.146    3.146
## 1   7.591   1.835    1.835
## 15 21.984   1.572    1.572
## 12 20.206   0.885    0.885
## 11 19.321   0.868    0.868
## 20 51.873   0.428    0.428
## 14 20.411   0.158    0.158
## 10 18.452   0.076    0.076
## 7  18.290   0.051    0.051
## 9  18.376   0.049    0.049
## 13 20.252   0.047    0.046
## 4  18.183   0.039    0.039
## 6  18.239   0.035    0.035
## 8  18.326   0.035    0.035
## 5  18.203   0.020    0.020
## [1] "Total Elapsed Time: 67.441 secs"

##                              label step_major step_minor label_minor
## 2   fit.models_0_Max.cor.Y.rcv.*X*          1          1      glmnet
## 3 fit.models_0_Interact.High.cor.Y          1          2      glmnet
## 4           fit.models_0_Low.cor.X          1          3      glmnet
## 1                 fit.models_0_bgn          1          0       setup
##      bgn    end elapsed duration
## 2 22.549 27.394   4.845    4.845
## 3 27.395 30.388   2.993    2.993
## 4 30.388 33.366   2.978    2.978
## 1 22.513 22.549   0.036    0.036
## [1] "Total Elapsed Time: 33.366 secs"